diff --git a/.editorconfig b/.editorconfig index 38ed8df1c..4d2b34c14 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,7 +13,7 @@ max_line_length = 100 [Dockerfile] indent_size = 4 -[Makefile] +[{Makefile,*.mk}] indent_style = tab indent_size = 8 @@ -23,8 +23,9 @@ indent_size = 4 [*.rs] indent_size = 4 -[*.S] -indent_size = 4 +[*.s] +indent_style = tab +indent_size = 8 [*.sh] indent_size = 4 diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 9696481b9..713818924 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -3,10 +3,8 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2018-2020 Andre Richter +# Copyright (c) 2018-2023 Andre Richter -require 'rubygems' -require 'bundler/setup' require_relative '../utils/devtool/copyright' def copyright_check(staged_files) @@ -14,6 +12,7 @@ def copyright_check(staged_files) staged_files = staged_files.select do |f| next if f.include?('build.rs') + next if f.include?('boot_test_string.rb') f.include?('Makefile') || f.include?('Dockerfile') || @@ -24,9 +23,9 @@ def copyright_check(staged_files) copyright_check_files(staged_files) end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Execution starts here -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- staged_files = `git --no-pager diff --name-only --cached --diff-filter=d`.split(/\n/) root_dir = `git rev-parse --show-toplevel`.strip diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..f6167fffd --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +### Description + + + +Related Issue: + +### Pre-commit steps + + - [ ] Tested on QEMU and real HW Rasperry Pi. + - Not needed if it is just a README change or similar. + - [ ] Ran `./contributor_setup.sh` followed by `./devtool ready_for_publish` + - You'll need `Ruby` with `Bundler` and `NPM` installed locally. + - If no Rust-related files were changed, `./devtool ready_for_publish_no_rust` can be used instead (faster). + - This step is optional, but much appreciated if done. diff --git a/.github/workflows/build_rpi3.yml b/.github/workflows/build_rpi3.yml index ec9a49e00..b3b997b3e 100644 --- a/.github/workflows/build_rpi3.yml +++ b/.github/workflows/build_rpi3.yml @@ -1,46 +1,40 @@ name: BSP-RPi3 on: - push: - branches: - - master - paths-ignore: - - "utils/**" - - "doc/**" - - "docker/**" - pull_request: - branches: - - master - paths-ignore: - - "utils/**" - - "doc/**" - - "docker/**" - schedule: - - cron: "0 5 * * *" + push: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + pull_request: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + schedule: + - cron: "0 5 * * *" jobs: - build: - name: Build kernels - runs-on: ubuntu-20.04 + build: + name: Build kernels + runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set up Ruby 2.x - uses: actions/setup-ruby@v1 - with: - ruby-version: "2.7" - - name: Set up Rust nightly - run: | - rustup self update - rustup toolchain install nightly --component llvm-tools-preview - rustup default nightly - rustup target add aarch64-unknown-none-softfloat - cargo install cargo-binutils - - name: Set up Ruby - run: | - gem install bundler - bundle config set without 'uart' - bundle install --retry 3 - - name: Make - run: | - BSP=rpi3 bundle exec ruby utils/devtool.rb make + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + - name: Set up Rust nightly + run: | + cargo install cargo-binutils rustfilt + - name: Set up Ruby + run: | + gem install bundler + bundle config set without 'uart' + bundle install --retry 3 + - name: Run + run: | + BSP=rpi3 bundle exec ruby utils/devtool.rb make diff --git a/.github/workflows/build_rpi4.yml b/.github/workflows/build_rpi4.yml index 12f8dc498..ca15786ed 100644 --- a/.github/workflows/build_rpi4.yml +++ b/.github/workflows/build_rpi4.yml @@ -1,46 +1,40 @@ name: BSP-RPi4 on: - push: - branches: - - master - paths-ignore: - - "utils/**" - - "doc/**" - - "docker/**" - pull_request: - branches: - - master - paths-ignore: - - "utils/**" - - "doc/**" - - "docker/**" - schedule: - - cron: "0 5 * * *" + push: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + pull_request: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + schedule: + - cron: "0 5 * * *" jobs: - build: - name: Build kernels - runs-on: ubuntu-20.04 + build: + name: Build kernels + runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set up Ruby 2.x - uses: actions/setup-ruby@v1 - with: - ruby-version: "2.7" - - name: Set up Rust nightly - run: | - rustup self update - rustup toolchain install nightly --component llvm-tools-preview - rustup default nightly - rustup target add aarch64-unknown-none-softfloat - cargo install cargo-binutils - - name: Set up Ruby - run: | - gem install bundler - bundle config set without 'uart' - bundle install --retry 3 - - name: Make - run: | - BSP=rpi4 bundle exec ruby utils/devtool.rb make + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + - name: Set up Rust nightly + run: | + cargo install cargo-binutils rustfilt + - name: Set up Ruby + run: | + gem install bundler + bundle config set without 'uart' + bundle install --retry 3 + - name: Run + run: | + BSP=rpi4 bundle exec ruby utils/devtool.rb make diff --git a/.github/workflows/sanity.yml b/.github/workflows/sanity.yml index 3d4d85625..3eb0f0888 100644 --- a/.github/workflows/sanity.yml +++ b/.github/workflows/sanity.yml @@ -1,51 +1,46 @@ name: Various Sanity Checks on: - push: - branches: - - master - pull_request: - branches: - - master + push: + branches: + - master + pull_request: + branches: + - master jobs: - build: - name: Various Sanity Checks - runs-on: ubuntu-20.04 + build: + name: Various Sanity Checks + runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set up Node - uses: actions/setup-node@v1 - with: - node-version: "12" - - name: Set up Ruby 2.x - uses: actions/setup-ruby@v1 - with: - ruby-version: "2.7" - - name: Set up Bundler - run: | - gem install bundler - bundle config set without 'uart' - bundle install --retry 3 - - name: Set up Prettier - run: | - npm install prettier - - name: Set up Rust nightly - run: | - rustup self update - rustup toolchain install nightly --component rustfmt clippy - rustup default nightly - rustup target add aarch64-unknown-none-softfloat - - name: Setup misspell - run: | - curl -L -o ./install-misspell.sh https://git.io/misspell - sh ./install-misspell.sh -b ~/bin - - name: Run checks - run: | - BSP=rpi3 bundle exec ruby utils/devtool.rb clippy - BSP=rpi4 bundle exec ruby utils/devtool.rb clippy - bundle exec ruby utils/devtool.rb copyright - bundle exec ruby utils/devtool.rb fmt_check - bundle exec ruby utils/devtool.rb misspell - bundle exec ruby utils/devtool.rb rubocop + steps: + - uses: actions/checkout@v3 + - name: Set up Node + uses: actions/setup-node@v1 + with: + node-version: "16" + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + - name: Set up Rust nightly + run: | + rustup component add clippy + - name: Set up Bundler + run: | + gem install bundler + bundle config set without 'uart' + bundle install --retry 3 + - name: Set up Prettier + run: | + npm install prettier + - name: Setup misspell + run: | + curl -L -o ./install-misspell.sh https://raw.githubusercontent.com/client9/misspell/master/install-misspell.sh + sh ./install-misspell.sh -b .vendor + - name: Run checks + run: | + BSP=rpi3 bundle exec ruby utils/devtool.rb clippy + BSP=rpi4 bundle exec ruby utils/devtool.rb clippy + bundle exec ruby utils/devtool.rb copyright + bundle exec ruby utils/devtool.rb fmt_check + bundle exec ruby utils/devtool.rb misspell + bundle exec ruby utils/devtool.rb rubocop diff --git a/.github/workflows/test_integration.yml b/.github/workflows/test_integration.yml index cf5d70082..7e3ab0764 100644 --- a/.github/workflows/test_integration.yml +++ b/.github/workflows/test_integration.yml @@ -1,46 +1,40 @@ name: Integration-Tests on: - push: - branches: - - master - paths-ignore: - - "utils/**" - - "doc/**" - - "docker/**" - pull_request: - branches: - - master - paths-ignore: - - "utils/**" - - "doc/**" - - "docker/**" - schedule: - - cron: "0 5 * * *" + push: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + pull_request: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + schedule: + - cron: "0 5 * * *" jobs: - build: - name: Run integration tests - runs-on: ubuntu-20.04 + build: + name: Run integration tests + runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set up Ruby 2.x - uses: actions/setup-ruby@v1 - with: - ruby-version: "2.7" - - name: Set up Rust nightly - run: | - rustup self update - rustup toolchain install nightly --component llvm-tools-preview - rustup default nightly - rustup target add aarch64-unknown-none-softfloat - cargo install cargo-binutils - - name: Set up Ruby - run: | - gem install bundler - bundle config set without 'uart' - bundle install --retry 3 - - name: Make all - run: | - bundle exec ruby utils/devtool.rb test_integration + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + - name: Set up Rust nightly + run: | + cargo install cargo-binutils rustfilt + - name: Set up Ruby + run: | + gem install bundler + bundle config set without 'uart' + bundle install --retry 3 + - name: Run + run: | + bundle exec ruby utils/devtool.rb test_integration diff --git a/.github/workflows/test_unit.yml b/.github/workflows/test_unit.yml index d090e8a4c..9ac564322 100644 --- a/.github/workflows/test_unit.yml +++ b/.github/workflows/test_unit.yml @@ -1,46 +1,41 @@ -name: Unit-Tests +name: Boot-and-Unit-Tests on: - push: - branches: - - master - paths-ignore: - - "utils/**" - - "doc/**" - - "docker/**" - pull_request: - branches: - - master - paths-ignore: - - "utils/**" - - "doc/**" - - "docker/**" - schedule: - - cron: "0 5 * * *" + push: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + pull_request: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + schedule: + - cron: "0 5 * * *" jobs: - build: - name: Run unit tests - runs-on: ubuntu-20.04 + build: + name: Run boot and unit tests + runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set up Ruby 2.x - uses: actions/setup-ruby@v1 - with: - ruby-version: "2.7" - - name: Set up Rust nightly - run: | - rustup self update - rustup toolchain install nightly --component llvm-tools-preview - rustup default nightly - rustup target add aarch64-unknown-none-softfloat - cargo install cargo-binutils - - name: Set up Ruby - run: | - gem install bundler - bundle config set without 'uart' - bundle install --retry 3 - - name: Make all - run: | - bundle exec ruby utils/devtool.rb test_unit + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + - name: Set up Rust nightly + run: | + cargo install cargo-binutils rustfilt + - name: Set up Ruby + run: | + gem install bundler + bundle config set without 'uart' + bundle install --retry 3 + - name: Run + run: | + bundle exec ruby utils/devtool.rb test_boot + bundle exec ruby utils/devtool.rb test_unit diff --git a/.github/workflows/test_xtra.yml b/.github/workflows/test_xtra.yml new file mode 100644 index 000000000..cdc705f9e --- /dev/null +++ b/.github/workflows/test_xtra.yml @@ -0,0 +1,40 @@ +name: Xtra-Tests + +on: + push: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + pull_request: + branches: + - master + paths-ignore: + - "utils/**" + - "doc/**" + - "docker/**" + schedule: + - cron: "0 5 * * *" + +jobs: + build: + name: Run xtra tests + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + - name: Set up Rust nightly + run: | + cargo install cargo-binutils + - name: Set up Ruby + run: | + gem install bundler + bundle config set without 'uart' + bundle install --retry 3 + - name: Run + run: | + bundle exec ruby utils/devtool.rb make_xtra diff --git a/.gitignore b/.gitignore index 196600522..5bc8cd8dd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,8 @@ **/kernel8.img node_modules +.bundle .vendor Gemfile.lock -package-lock.json +package*.json diff --git a/.prettierrc.json b/.prettierrc.json index 0967ef424..864ccc367 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1 +1,35 @@ -{} +{ + "printWidth": 100, + "tabWidth": 4, + "useTabs": false, + "semi": true, + "singleQuote": false, + "trailingComma": "es5", + "bracketSpacing": true, + "jsxBracketSameLine": false, + "arrowParens": "always", + "requirePragma": false, + "insertPragma": false, + "proseWrap": "preserve", + "endOfLine": "auto", + "overrides": [ + { + "files": "*.rs", + "options": { + "printWidth": 100, + "tabWidth": 4, + "useTabs": false, + "semi": true, + "singleQuote": false, + "trailingComma": "es5", + "bracketSpacing": true, + "jsxBracketSameLine": false, + "arrowParens": "always", + "requirePragma": false, + "insertPragma": false, + "proseWrap": "preserve", + "endOfLine": "auto" + } + } + ] +} diff --git a/.rubocop.yml b/.rubocop.yml index 78ba1c1d6..059ba16e2 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -10,16 +10,23 @@ # See https://github.com/rubocop-hq/rubocop/blob/master/manual/configuration.md Layout/IndentationWidth: - Width: 4 + Width: 4 + AllowedPatterns: ['^\s*module'] Layout/LineLength: - Max: 100 + Max: 100 + +Lint/UnusedMethodArgument: + AutoCorrect: False + +Metrics/AbcSize: + Max: 25 Metrics/ClassLength: - Enabled: false + Enabled: false Metrics/MethodLength: - Max: 20 + Max: 20 AllCops: - NewCops: enable + NewCops: enable diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 000000000..b50214693 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.0.2 diff --git a/.rustfmt.toml b/.rustfmt.toml index 25a745377..c05f18179 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,9 +1,7 @@ newline_style = "Unix" -edition = "2018" -merge_imports = true +edition = "2021" +imports_granularity = "Crate" format_code_in_doc_comments = true normalize_comments = true wrap_comments = true comment_width = 100 -report_fixme = "Always" -report_todo = "Always" diff --git a/.vscode/settings.json b/.vscode/settings.json index d77cd3373..9ef30cd06 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,10 @@ { - "editor.formatOnSave": true, - "editor.rulers": [100] + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false } diff --git a/00_before_we_start/README.CN.md b/00_before_we_start/README.CN.md index 8d609d00f..f36182d41 100644 --- a/00_before_we_start/README.CN.md +++ b/00_before_we_start/README.CN.md @@ -2,7 +2,7 @@ 下面的文本内容是1:1 复制的文档。在每个教程的内核主要源代码文档的头部。它描述了源代码的主要结构并且试着去传达各个方法背后的理念。请阅读文章以便你能熟悉你在教程中将会遇到的东西。这将帮助你更好的浏览代码和理解不同章节的区别和增量内容。 -另请注意,以下文字将引用源代码文件(例如`** / memory.rs`)或在本教程的第一批教程中尚不存在的功能。 它们将被逐渐添加到本教程。 +另请注意,以下文字将引用源代码文件(例如`**/memory.rs`)或在本教程的第一批教程中尚不存在的功能。 它们将被逐渐添加到本教程。 玩的开心! @@ -14,7 +14,7 @@ 有的内核的子系统是基于特定目标架构的处理器的低级代码。对于每种支持的处理器架构,都有一个子文件夹在`src/_arch`中。例如,`src/_arch/aarch64` -子模块系统在每个处理器架构的`src`文件夹中。例如,属于内核内存子系统(`src/memory.rs`)的代码将会被放在`src/_arch/aarch64/memory.rs`.后一个文件将被直接包含和重新导出到`src/memory.ts`中,以便架构代码部分是明显的遵循代码模块话。这意味着在`src/_arch/aarch64/memory.rs`中定义的公共函数foo()。仅可通过`crate :: memory :: foo()`访问。 +子模块系统在每个处理器架构的`src`文件夹中。例如,属于内核内存子系统(`src/memory.rs`)的代码将会被放在`src/_arch/aarch64/memory.rs`.后一个文件将被直接包含和重新导出到`src/memory.rs`中,以便架构代码部分是明显的遵循代码模块化。这意味着在`src/_arch/aarch64/memory.rs`中定义的公共函数foo()。仅可通过`crate :: memory :: foo()`访问。 `_arch`中的`_`表示此文件夹不属于标准模块层次结构。而是使用`#[path =“ _ arch/xxx/yyy.rs”]`属性将其内容有条件地引入各自的文件中。 diff --git a/00_before_we_start/README.ES.md b/00_before_we_start/README.ES.md new file mode 100644 index 000000000..9b589a5a3 --- /dev/null +++ b/00_before_we_start/README.ES.md @@ -0,0 +1,103 @@ +# Antes de comenzar + +El texto a continuación es una copia 1:1 de la documentación que +puede ser encontrada al principio del archivo del código fuente +del núcleo (kernel) en cada tutorial. Esta describe la estructura +general del código fuente, e intenta transmitir la filosofía detrás +de cada enfoque. Por favor leélo para familiarizarte +con lo que te vas a encontrar durante los tutoriales. Te ayudará a navegar el código de una mejor manera y a entender las diferencias y agregados entre los diferentes tutoriales. + +Por favor, nota también que el siguiente texto va a referenciar +los archivos del código fuente (p. e.j. `**/memory.rs`) o funciones que +no van a existir aún en los primeros tutoriales. Estos archivos serán agregados +a medida que el tutorial avance. + +¡Diviértanse! + +# La estructura del código y la arquitectura + +El código está dividido en diferentes módulos donde cada uno representa un +subsistema típico del `kernel (núcleo)`. Los módulos de más alto nivel de los subsistemas se encuentran directamente en la carpeta `src`. +Por ejemplo, `src/memory.rs` contiene el código que está relacionado +con el manejo de memoria. + +## Visibilidad del código de arquitectura del procesador + +Algunos de los subsistemas del `núcleo (kernel)` dependen del código de bajo nivel (low-level) dedicado a la arquitectura del procesador. +Por cada arquitectura de procesador que está soportada, existe una subcarpeta en `src/_arch`, por ejemplo, `src/_arch/aarch64`. + +La carpeta de arquitecturas refleja los módulos del subsistema establecidos en `src`. Por ejemplo, el código de arquitectura que pertenece al subsistema MMU del `núcleo(kernel)` (`src/memory/mmu.rs`) irá dentro de (`src/_arch/aarch64/memory/mmu.rs`). +Este archivo puede ser cargado como un módulo en `src/memory/mmu.rs` usando el `path attribute` (atributo de ruta). Usualmente, el nombre del módulo elegido es el nombre del módulo genérico con el prefijo de `arch_` + +Por ejemplo, esta es la parte superior de `src/memory/mmu.rs`: + +``` +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; +``` + +En muchas ocasiones, los elementos de `arch_module` serán reexportados públicamente por el módulo principal. +De esta manera, cada módulo específico de la arquitectura puede proporcionar su implementación de un elemento, mientras que el *invocante* no debe de preocuparse por la arquitectura que se ha compilado condicionalmente. + +## Código BSP + +`BSP` significa Board Support Package (Paquete de Soporte de la Placa). +El código `BSP` está dentro de `src/bsp.rs` y contiene las definiciones y funciones de la placa base específica elegida. +Entre estas cosas se encuentran diferentes elementos como el mapa de memoria de la placa o instancias de controladores para dispositivos que se presentan en la placa elegida. + +Justo como el código de la arquitectura del procesador, la estructura del módulo del código `BSP` trata de reflejar los módulos del subsistema del `núcleo (kernel)`, pero no ocurre una reexportación esta vez. Eso significa que lo que sea que se esté proporcionando debe ser llamado empezando por el *namespace* (espacio de nombres) de `bsp`, p. ej. `bsp::driver::driver_manager()`. + +## La interfaz del núcleo (kernel) + +El `arch` y el `bsp` contienen código que se compilará condicionalmente dependiendo del procesador y placa actual para la que se compila el núcleo (kernel). +Por ejemplo, el hardware de control de interrupciones de la `Raspberry Pi 3` y la `Raspberry Pi 4` es diferente, pero nosotros queremos que el resto del código del kernel funcione correctamente con cualquiera de los dos sin mucha complicación. + +Para poder dar una limpia abstracción entre `arch`, `bsp` y código genérico del núcleo, los rasgos de `interface` se proporcionan *siempre y cuando tenga sentido*. Son definidos en su módulo de subsistema correspondiente y ayuda a reforzar el patrón de programar con respecto a una interfaz, sin importar la implementación concreta. + +Por ejemplo, habrá una *IRQ handling interface* (interfaz de manejo de interrupciones) común, el cual los dos diferentes controladores de ambas `Raspberry` implementarán, y solo exportarán la interfaz común al resto del `núcleo (kernel)`. + +``` + +-------------------+ + | Interface (Trait) | + | | + +--+-------------+--+ + ^ ^ + | | + | | ++----------+--+ +--+----------+ +| kernel code | | bsp code | +| | | arch code | ++-------------+ +-------------+ +``` + +# Resumen + +Para un subsistema lógico del `núcleo (kernel)`, el código correspondiente puede ser distribuido sobre diferentes localizaciones físicas. Aquí un ejemplo para el subsistema de memoria: + +- `src/memory.rs` y `src/memory/**/*` + + - Código común que es independiente de la arquitectura del procesador de destino y las características de la placa (`BSP`). + - Ejemplo: Una función para poner a cero un trozo de memoria. + - Las interfaces para el subsistema de la memoria que son implementados por código de `arch` o `BSP`. + - Ejemplo: Una interfaz `MMU` que define prototipos de función de `MMU`. + +- `src/bsp/__board_name__/memory.rs` y `src/bsp/__board_name__/memory/**/*` + + - Código específico de `BSP`. + - Ejemplo: El mapa de memoria de la placa (direcciones físicas de DRAM y dispositivos MMIO). + +- `src/_arch/__arch_name__/memory.rs` y `src/_arch/__arch_name__/memory/**/*` + + - El código específico de la arquitectura del procesador. + - Ejemplo: Implementación de la interfaz `MMU` para la arquitectura `__arch_name__`. + +Desde una perspectiva de *namespace*, el código del subsistema de **memoria** vive en: + +- `crate::memory::*` +- `crate::bsp::memory::*` + +# Flujo de Boot / Boot flow + +1. El punto de entrada del núcleo (kernel) es la función `cpu::boot::arch_boot::_start()`. + - Está implementado en `src/_arch/__arch_name__/cpu/boot.s`. diff --git a/00_before_we_start/README.md b/00_before_we_start/README.md index 02c25118e..9e79caf4b 100644 --- a/00_before_we_start/README.md +++ b/00_before_we_start/README.md @@ -12,7 +12,7 @@ the tutorials advance. Have fun! -## Code organization and architecture +# Code organization and architecture The code is divided into different *modules*, each representing a typical **subsystem** of the `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, @@ -25,15 +25,22 @@ architecture. For each supported processor architecture, there exists a subfolde for example, `src/_arch/aarch64`. The architecture folders mirror the subsystem modules laid out in `src`. For example, architectural -code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go into -`src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -`src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -module organization. That means a public function `foo()` defined in `src/_arch/aarch64/memory.rs` -would be reachable as `crate::memory::foo()` only. +code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go into +`src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in `src/memory/mmu.rs` +using the `path attribute`. Usually, the chosen module name is the generic module's name prefixed +with `arch_`. -The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. Rather, -it's contents are conditionally pulled into respective files using the `#[path = -"_arch/xxx/yyy.rs"]` attribute. +For example, this is the top of `src/memory/mmu.rs`: + +``` +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; +``` + +Often times, items from the `arch_ module` will be publicly reexported by the parent module. This +way, each architecture specific module can provide its implementation of an item, while the caller +must not be concerned which architecture has been conditionally compiled. ## BSP code @@ -42,9 +49,8 @@ target board specific definitions and functions. These are things such as the bo instances of drivers for devices that are featured on the respective board. Just like processor architecture code, the `BSP` code's module structure tries to mirror the -`kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -whatever is provided must be called starting from the `bsp` namespace, e.g. -`bsp::driver::driver_manager()`. +`kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is provided +must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. ## Kernel interfaces @@ -96,3 +102,10 @@ From a namespace perspective, **memory** subsystem code lives in: - `crate::memory::*` - `crate::bsp::memory::*` + +# Boot flow + +1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. + - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. + + diff --git a/01_wait_forever/.vscode/settings.json b/01_wait_forever/.vscode/settings.json index a0d6a9202..bfa278e9a 100644 --- a/01_wait_forever/.vscode/settings.json +++ b/01_wait_forever/.vscode/settings.json @@ -1,7 +1,10 @@ { - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false } diff --git a/01_wait_forever/Cargo.lock b/01_wait_forever/Cargo.lock index 3e9c31110..aaed18257 100644 --- a/01_wait_forever/Cargo.lock +++ b/01_wait_forever/Cargo.lock @@ -1,6 +1,7 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + [[package]] -name = "kernel" +name = "mingo" version = "0.1.0" - diff --git a/01_wait_forever/Cargo.toml b/01_wait_forever/Cargo.toml index 0f798fcbe..c2815c329 100644 --- a/01_wait_forever/Cargo.toml +++ b/01_wait_forever/Cargo.toml @@ -1,20 +1,23 @@ [package] -name = "kernel" +name = "mingo" version = "0.1.0" authors = ["Andre Richter "] -edition = "2018" +edition = "2021" [profile.release] lto = true -# The features section is used to select the target board. [features] default = [] bsp_rpi3 = [] bsp_rpi4 = [] +[[bin]] +name = "kernel" +path = "src/main.rs" + ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- -[dependencies] +[dependencies] \ No newline at end of file diff --git a/01_wait_forever/Makefile b/01_wait_forever/Makefile index 1481f8a45..51c128f7c 100644 --- a/01_wait_forever/Makefile +++ b/01_wait_forever/Makefile @@ -1,11 +1,25 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2020 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -# Default to the RPi3 +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. BSP ?= rpi3 -# BSP-specific arguments + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img @@ -14,7 +28,8 @@ ifeq ($(BSP),rpi3) QEMU_RELEASE_ARGS = -d in_asm -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat @@ -24,75 +39,154 @@ else ifeq ($(BSP),rpi4) QEMU_RELEASE_ARGS = -d in_asm -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif -# Export for build.rs -export LINKER_FILE +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ + $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary -KERNEL_ELF = target/$(TARGET)/release/kernel +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu clippy clean readelf objdump nm check -all: $(KERNEL_BIN) +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu clippy clean readelf objdump nm check -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) +all: $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ doc: - $(DOC_CMD) --document-private-items --open + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. -ifeq ($(QEMU_MACHINE_TYPE),) qemu: - @echo "This board is not yet supported for QEMU." -else + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/01_wait_forever/README.CN.md b/01_wait_forever/README.CN.md index 281a92903..06b2178d5 100644 --- a/01_wait_forever/README.CN.md +++ b/01_wait_forever/README.CN.md @@ -14,7 +14,7 @@ - `nm`: 检查符号。 - 代码按照 `kernel`, `arch` 和 `BSP` (板级支持包)的形式组织。 - 条件编译会根据用户提供的参数编译各自的 `arch` 和 `BSP` 的内容。 -- 自定义 `link.ld` 链接脚本. +- 自定义 `kernel.ld` 链接脚本. - 载入地址为 `0x80_000` - 目前仅有 `.text` 小节(section)。 - `main.rs`: 重要的 [inner attributes]: diff --git a/01_wait_forever/README.ES.md b/01_wait_forever/README.ES.md new file mode 100644 index 000000000..0d86a4ea4 --- /dev/null +++ b/01_wait_forever/README.ES.md @@ -0,0 +1,55 @@ +# Tutorial 01 - Esperar infinitamente + +## tl;dr + +* Se configura la estructura que tiene el proyecto. + +* Se ejecuta una pequeño código hecho en ensamblador que tiene como función detener todos los núcleos del procesador que están ejecutando el kernel. + +## Compilar + +* El archivo `Makefile` permite ejecutar: + + * `doc`: Genera la documentación. + + * `qemu`: Ejecutar el kernel en QEMU. + + * `clippy`: Analiza el código y sugiere mejoras. + + * `clean`: Elimina todos los archivos generados durante la compilación, etc. + + * `readelf`: Inspecciona el archivo `ELF` de salida. + + * `objdump`: Inspecciona el ensamblador. + + * `nm`: Inspecciona los símbolos. + +## Código a revisar + +* El script para enlazado específico para la `BSP` llamado `kernel.ld`. + + * Carga la dirección en `0x8_0000`. + + * Solo la sección `.text`. + +* `main.rs`: [Atributos internos](https://doc.rust-lang.org/reference/attributes.html) importantes: + + * `#![no_std]`, `#![no_main]`. + +* `boot.s`: La función de ensamblador `_start()` que inicia `wfe` (Wait For Event / Esperar Hasta Un Evento), detiene todos los núcleos del procesador que están ejecutando `_start()`. + +* Tenemos que definir una función que funcione como `#[panic_handler]` (manejador de pánico) para que el compilador no nos cause problemas. + + * Hazla `unimplemented!()` porque se eliminará ya que no está siendo usada. + +## Pruébalo + +Dentro de la carpeta del proyecto, ejecuta a QEMU y mira el núcleo del procesador ejecutando `wfe` en bucle: + +``` +$ make qemu +[...] +IN: +0x00080000: d503205f wfe +0x00080004: 17ffffff b #0x80000 +``` diff --git a/01_wait_forever/README.md b/01_wait_forever/README.md index b1927c9bb..73b15af5c 100644 --- a/01_wait_forever/README.md +++ b/01_wait_forever/README.md @@ -18,21 +18,22 @@ ## Code to look at -- Custom `link.ld` linker script. +- `BSP`-specific `kernel.ld` linker script. - Load address at `0x8_0000` - Only `.text` section. - `main.rs`: Important [inner attributes]: - `#![no_std]`, `#![no_main]` -- `cpu.S`: Assembly `_start()` function that executes `wfe` (Wait For Event), halting all cores that - are executing `_start()`. -- We (have to) define a `#[panic_handler]` function. - - Just waits infinitely for a cpu event. +- `boot.s`: Assembly `_start()` function that executes `wfe` (Wait For Event), halting all cores + that are executing `_start()`. +- We (have to) define a `#[panic_handler]` function to make the compiler happy. + - Make it `unimplemented!()` because it will be stripped out since it is not used. [inner attributes]: https://doc.rust-lang.org/reference/attributes.html ### Test it In the project folder, invoke QEMU and observe the CPU core spinning on `wfe`: + ```console $ make qemu [...] diff --git a/01_wait_forever/build.rs b/01_wait_forever/build.rs index 40ee0284d..cab00bb37 100644 --- a/01_wait_forever/build.rs +++ b/01_wait_forever/build.rs @@ -1,7 +1,20 @@ -use std::env; +use std::{env, fs, process}; fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; - println!("cargo:rerun-if-changed={}", linker_file); + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); } diff --git a/01_wait_forever/src/_arch/aarch64/cpu.S b/01_wait_forever/src/_arch/aarch64/cpu.S deleted file mode 100644 index bd80689c7..000000000 --- a/01_wait_forever/src/_arch/aarch64/cpu.S +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -.section ".text._start" - -.global _start - -_start: -1: wfe // Wait for event - b 1b // In case an event happened, jump back to 1 diff --git a/01_wait_forever/src/_arch/aarch64/cpu.rs b/01_wait_forever/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 1d3e871a6..000000000 --- a/01_wait_forever/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -// Assembly counterpart to this file. -global_asm!(include_str!("cpu.S")); - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - unsafe { - loop { - #[rustfmt::skip] - asm!( - "wfe", - options(nomem, nostack, preserves_flags) - ); - } - } -} diff --git a/01_wait_forever/src/_arch/aarch64/cpu/boot.rs b/01_wait_forever/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..3cf9b08fb --- /dev/null +++ b/01_wait_forever/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!(include_str!("boot.s")); diff --git a/01_wait_forever/src/_arch/aarch64/cpu/boot.s b/01_wait_forever/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..8f33b483d --- /dev/null +++ b/01_wait_forever/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/01_wait_forever/src/bsp.rs b/01_wait_forever/src/bsp.rs index db48385eb..b128add9b 100644 --- a/01_wait_forever/src/bsp.rs +++ b/01_wait_forever/src/bsp.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter -//! Conditional re-exporting of Board Support Packages. +//! Conditional reexporting of Board Support Packages. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; diff --git a/01_wait_forever/src/bsp/raspberrypi.rs b/01_wait_forever/src/bsp/raspberrypi.rs index cdaac7405..3253ee5e9 100644 --- a/01_wait_forever/src/bsp/raspberrypi.rs +++ b/01_wait_forever/src/bsp/raspberrypi.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. diff --git a/01_wait_forever/src/bsp/raspberrypi/kernel.ld b/01_wait_forever/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..8f79ff76d --- /dev/null +++ b/01_wait_forever/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + */ +PHDRS +{ + segment_code PT_LOAD FLAGS(5); +} + +SECTIONS +{ + . = __rpi_phys_binary_load_addr; + + /*********************************************************************************************** + * Code + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + } :segment_code +} diff --git a/01_wait_forever/src/bsp/raspberrypi/link.ld b/01_wait_forever/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c95db067b..000000000 --- a/01_wait_forever/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,17 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/01_wait_forever/src/cpu.rs b/01_wait_forever/src/cpu.rs index fd5c9794e..9f399de24 100644 --- a/01_wait_forever/src/cpu.rs +++ b/01_wait_forever/src/cpu.rs @@ -1,10 +1,7 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; +mod boot; diff --git a/01_wait_forever/src/cpu/boot.rs b/01_wait_forever/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/01_wait_forever/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/01_wait_forever/src/main.rs b/01_wait_forever/src/main.rs index 28b68b59f..10fdb3f43 100644 --- a/01_wait_forever/src/main.rs +++ b/01_wait_forever/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] //! The `kernel` binary. //! @@ -20,15 +22,22 @@ //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. //! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! @@ -37,9 +46,8 @@ //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! @@ -91,14 +99,15 @@ //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. -#![feature(asm)] -#![feature(global_asm)] #![no_main] #![no_std] -// `mod cpu` provides the `_start()` function, the first function to run. - mod bsp; mod cpu; mod panic_wait; diff --git a/01_wait_forever/src/panic_wait.rs b/01_wait_forever/src/panic_wait.rs index 560a1724e..714bf2963 100644 --- a/01_wait_forever/src/panic_wait.rs +++ b/01_wait_forever/src/panic_wait.rs @@ -1,13 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. -use crate::cpu; use core::panic::PanicInfo; +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + #[panic_handler] fn panic(_info: &PanicInfo) -> ! { - cpu::wait_forever() + unimplemented!() } diff --git a/02_runtime_init/.vscode/settings.json b/02_runtime_init/.vscode/settings.json index a0d6a9202..bfa278e9a 100644 --- a/02_runtime_init/.vscode/settings.json +++ b/02_runtime_init/.vscode/settings.json @@ -1,7 +1,10 @@ { - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false } diff --git a/02_runtime_init/Cargo.lock b/02_runtime_init/Cargo.lock index 3e9c31110..e52e7fdf1 100644 --- a/02_runtime_init/Cargo.lock +++ b/02_runtime_init/Cargo.lock @@ -1,6 +1,25 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + [[package]] -name = "kernel" -version = "0.1.0" +name = "mingo" +version = "0.2.0" +dependencies = [ + "aarch64-cpu", +] +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/02_runtime_init/Cargo.toml b/02_runtime_init/Cargo.toml index 0f798fcbe..5946f43ca 100644 --- a/02_runtime_init/Cargo.toml +++ b/02_runtime_init/Cargo.toml @@ -1,20 +1,27 @@ [package] -name = "kernel" -version = "0.1.0" +name = "mingo" +version = "0.2.0" authors = ["Andre Richter "] -edition = "2018" +edition = "2021" [profile.release] lto = true -# The features section is used to select the target board. [features] default = [] bsp_rpi3 = [] bsp_rpi4 = [] +[[bin]] +name = "kernel" +path = "src/main.rs" + ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/02_runtime_init/Makefile b/02_runtime_init/Makefile index 1481f8a45..893564e2d 100644 --- a/02_runtime_init/Makefile +++ b/02_runtime_init/Makefile @@ -1,11 +1,25 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2020 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -# Default to the RPi3 +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. BSP ?= rpi3 -# BSP-specific arguments + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img @@ -14,7 +28,8 @@ ifeq ($(BSP),rpi3) QEMU_RELEASE_ARGS = -d in_asm -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat @@ -24,75 +39,155 @@ else ifeq ($(BSP),rpi4) QEMU_RELEASE_ARGS = -d in_asm -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif -# Export for build.rs -export LINKER_FILE +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ + $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary -KERNEL_ELF = target/$(TARGET)/release/kernel +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu clippy clean readelf objdump nm check -all: $(KERNEL_BIN) +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu clippy clean readelf objdump nm check -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) +all: $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ doc: - $(DOC_CMD) --document-private-items --open + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. -ifeq ($(QEMU_MACHINE_TYPE),) qemu: - @echo "This board is not yet supported for QEMU." -else + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/02_runtime_init/README.CN.md b/02_runtime_init/README.CN.md index eb932091d..0272e057c 100644 --- a/02_runtime_init/README.CN.md +++ b/02_runtime_init/README.CN.md @@ -2,198 +2,29 @@ ## tl;dr -我们拓展了`cpu.S`,在第一次启动的时候调用Rust代码。在Rust的代码中先清零了[bss] section,然后通过调用`panic()`挂起CPU。再次运行`make qemu`看看新增加的代码是怎么运行的。 +- 我们拓展了`boot.S`,在第一次启动的时候调用Rust代码。 + 在跳转到rust代码前,对运行时进行了一些初始化工作。 +- Rust通过调用`panic()`挂起CPU。 +- 再次运行`make qemu`看看新增加的代码是怎么运行的。 ## 值得注意的变化 -- 链接脚本(linker script)中有了更多的section。 - - `.rodata`, `.data` - - `.bss` -- `_start()`: - - 当核心不是`core0`第0号核心的时候,挂起该CPU核心。 - - `core0`会调用Rust的函数`runtime_init()`。 -- `runtime_init.rs`内的`runtime_init()` - - 清零了`.bss` section. - - 它调用了`kernel_init()`, 这个函数又调用了`panic!()`, panic函数最终把`core0`和其他核心一样挂起了。 +- 链接脚本(linker script)中的变化: + - 新程序段(sections): `.rodata`, `.got`, `.data`, `.bss`. + - 使用一个独立的位置(`.text._start_arguments`)来保存`_start()`引导函数所使用的参数。 +- `_start()` in `_arch/__arch_name__/cpu/boot.s`: + 1. 当核心不是`core0`第0号核心的时候,挂起该CPU核心。 + 1. 通过清零`.bss`程序段来初始化`DRAM`. + 1. 初始化堆栈指针(`stack pointer`). + 1. 跳转到`arch/__arch_name__/cpu/boot.rs`文件中定义的`_start_rust()`函数 +- `_start_rust()`: + 1. 它调用了`kernel_init()`, 这个函数又调用了`panic!()`, panic函数最终把`core0`和其他核心一样挂起了。 +- 目前依赖 [aarch64-cpu] 程序库, 这个库零成本的包装了处理 CPU 资源时的“不安全”部分。 + - 详细请参考 `_arch/__arch_name__/cpu.rs`. [bss]: https://en.wikipedia.org/wiki/.bss +[aarch64-cpu]: https://github.com/rust-embedded/aarch64-cpu ## 相比之前的变化(diff) -```diff +请检查[英文版本](README.md#diff-to-previous),这是最新的。 -diff -uNr 01_wait_forever/src/_arch/aarch64/cpu.S 02_runtime_init/src/_arch/aarch64/cpu.S ---- 01_wait_forever/src/_arch/aarch64/cpu.S -+++ 02_runtime_init/src/_arch/aarch64/cpu.S -@@ -7,5 +7,15 @@ - .global _start - - _start: --1: wfe // Wait for event -- b 1b // In case an event happened, jump back to 1 -+ mrs x1, mpidr_el1 // Read Multiprocessor Affinity Register -+ and x1, x1, #3 // Clear all bits except [1:0], which hold core id -+ cbz x1, 2f // Jump to label 2 if we are core 0 -+1: wfe // Wait for event -+ b 1b // In case an event happened, jump back to 1 -+2: // If we are here, we are core0 -+ ldr x1, =_start // Load address of function "_start()" -+ mov sp, x1 // Set start of stack to before our code, aka first -+ // address before "_start()" -+ bl runtime_init // Jump to the "runtime_init()" kernel function -+ b 1b // We should never reach here. But just in case, -+ // park this core aswell - -diff -uNr 01_wait_forever/src/bsp/raspberrypi/link.ld 02_runtime_init/src/bsp/raspberrypi/link.ld ---- 01_wait_forever/src/bsp/raspberrypi/link.ld -+++ 02_runtime_init/src/bsp/raspberrypi/link.ld -@@ -13,5 +13,24 @@ - *(.text._start) *(.text*) - } - -+ .rodata : -+ { -+ *(.rodata*) -+ } -+ -+ .data : -+ { -+ *(.data*) -+ } -+ -+ /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ -+ .bss ALIGN(8): -+ { -+ __bss_start = .; -+ *(.bss*); -+ . = ALIGN(8); -+ __bss_end = .; -+ } -+ - /DISCARD/ : { *(.comment*) } - } - -diff -uNr 01_wait_forever/src/main.rs 02_runtime_init/src/main.rs ---- 01_wait_forever/src/main.rs -+++ 02_runtime_init/src/main.rs -@@ -97,10 +97,20 @@ - #![no_main] - #![no_std] - --// `mod cpu` provides the `_start()` function, the first function to run. -+// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -+// `runtime_init()`, which jumps to `kernel_init()`. - - mod bsp; - mod cpu; -+mod memory; - mod panic_wait; -+mod runtime_init; - --// Kernel code coming next tutorial. -+/// Early init code. -+/// -+/// # Safety -+/// -+/// - Only a single core must be active and running this function. -+unsafe fn kernel_init() -> ! { -+ panic!() -+} - -diff -uNr 01_wait_forever/src/memory.rs 02_runtime_init/src/memory.rs ---- 01_wait_forever/src/memory.rs -+++ 02_runtime_init/src/memory.rs -@@ -0,0 +1,29 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Memory Management. -+ -+use core::ops::Range; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Zero out a memory region. -+/// -+/// # Safety -+/// -+/// - `range.start` and `range.end` must be valid. -+/// - `range.start` and `range.end` must be `T` aligned. -+pub unsafe fn zero_volatile(range: Range<*mut T>) -+where -+ T: From, -+{ -+ let mut ptr = range.start; -+ -+ while ptr < range.end { -+ core::ptr::write_volatile(ptr, T::from(0)); -+ ptr = ptr.offset(1); -+ } -+} - -diff -uNr 01_wait_forever/src/runtime_init.rs 02_runtime_init/src/runtime_init.rs ---- 01_wait_forever/src/runtime_init.rs -+++ 02_runtime_init/src/runtime_init.rs -@@ -0,0 +1,58 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Rust runtime initialization code. -+ -+use crate::memory; -+use core::ops::Range; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return the range spanning the .bss section. -+/// -+/// # Safety -+/// -+/// - The symbol-provided addresses must be valid. -+/// - The symbol-provided addresses must be usize aligned. -+unsafe fn bss_range() -> Range<*mut usize> { -+ extern "C" { -+ // Boundaries of the .bss section, provided by linker script symbols. -+ static mut __bss_start: usize; -+ static mut __bss_end: usize; -+ } -+ -+ Range { -+ start: &mut __bss_start, -+ end: &mut __bss_end, -+ } -+} -+ -+/// Zero out the .bss section. -+/// -+/// # Safety -+/// -+/// - Must only be called pre `kernel_init()`. -+#[inline(always)] -+unsafe fn zero_bss() { -+ memory::zero_volatile(bss_range()); -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -+/// init code. -+/// -+/// # Safety -+/// -+/// - Only a single core must be active and running this function. -+#[no_mangle] -+pub unsafe extern "C" fn runtime_init() -> ! { -+ zero_bss(); -+ -+ crate::kernel_init() -+} - -``` diff --git a/02_runtime_init/README.ES.md b/02_runtime_init/README.ES.md new file mode 100644 index 000000000..2f93586f9 --- /dev/null +++ b/02_runtime_init/README.ES.md @@ -0,0 +1,37 @@ +# Tutorial 02 - Inicialización del `runtime` + +## tl;dr + +* Extendimos la funcionalidad de `boot.s` para que sea capaz de llamar código Rust por primera vez. Antes de que el cambio a Rust ocurra, se realizan algunos trabajos de inicialización del `runtime` (soporte para ejecución de código). +* El código Rust que es llamado solo pausa la ejecución con una llamada a `panic!()`. +* Ejecuta `make qemu` de nuevo para que puedas ver el código adicional en acción. + +## Adiciones importantes + +* Adiciones importantes al script `kernel.ld`: + + * Nuevas secciones: `.rodata`, `.got`, `.data`, `.bss`. + + * Un lugar totalmente dedicado a enlazar argumentos de tiempo de arranque (boot-time) que necesitan estar listos cuando se llame a `_start()`. + +* `_start()` en `_arch/__arch_name__/cpu/boot.s`: + + 1. Para todos los núcleos expecto el núcleo 0. + + 2. Inicializa la [`DRAM`](https://es.wikipedia.org/wiki/DRAM) poniendo a cero la sección [`.bss`](https://en.wikipedia.org/wiki/.bss). + + 3. Configura el `stack pointer` (puntero a la memoria [pila](https://es.wikipedia.org/wiki/Pila_(inform%C3%A1tica))). + + 4. Salta hacia la función `_start_rust()`, definida en `arch/__arch_name__/cpu/boot.rs`. + +* `_start_rust()`: + + * Llama a `kernel_init()`, que llama a `panic!()`, que al final también pone al núcleo 0 en pausa. + +* La librería ahora usa el crate [aarch64-cpu](https://github.com/rust-embedded/aarch64-cpu), que nos da abstracciones sin coste y envuelve las partes que hacen uso de un `unsafe` (partes con código que no es seguro y podría causar errores) cuando se trabaja directamente con los recursos del procesador. + + * Lo puedes ver en acción en `_arch/__arch_name__/cpu.rs`. + +## Diferencia con el archivo anterior + +Please check [the english version](README.md#diff-to-previous), which is kept up-to-date. diff --git a/02_runtime_init/README.md b/02_runtime_init/README.md index e54520cd3..1082f18c6 100644 --- a/02_runtime_init/README.md +++ b/02_runtime_init/README.md @@ -2,122 +2,282 @@ ## tl;dr -- We extend `cpu.S` to call into Rust code for the first time. There, we zero the [bss] section - before execution is halted with a call to `panic()`. +- We extend `boot.s` to call into Rust code for the first time. Before the jump + to Rust happens, a bit of runtime init work is done. +- The Rust code being called just halts execution with a call to `panic!()`. - Check out `make qemu` again to see the additional code run. ## Notable additions -- More sections in linker script: - - `.rodata`, `.data` - - `.bss` -- `_start()`: - - Halt core if core != `core0`. - - `core0` jumps to the `runtime_init()` Rust function. -- `runtime_init()` in `runtime_init.rs` - - Zeros the `.bss` section. - - Calls `kernel_init()`, which calls `panic!()`, which eventually halts `core0` as well. +- More additions to the linker script: + - New sections: `.rodata`, `.got`, `.data`, `.bss`. + - A dedicated place for linking boot-time arguments that need to be read by `_start()`. +- `_start()` in `_arch/__arch_name__/cpu/boot.s`: + 1. Halts core if core != core0. + 1. Initializes the `DRAM` by zeroing the [bss] section. + 1. Sets up the `stack pointer`. + 1. Jumps to the `_start_rust()` function, defined in `arch/__arch_name__/cpu/boot.rs`. +- `_start_rust()`: + - Calls `kernel_init()`, which calls `panic!()`, which eventually halts core0 as well. +- The library now uses the [aarch64-cpu] crate, which provides zero-overhead abstractions and wraps + `unsafe` parts when dealing with the CPU's resources. + - See it in action in `_arch/__arch_name__/cpu.rs`. [bss]: https://en.wikipedia.org/wiki/.bss +[aarch64-cpu]: https://github.com/rust-embedded/aarch64-cpu ## Diff to previous ```diff -diff -uNr 01_wait_forever/src/_arch/aarch64/cpu.S 02_runtime_init/src/_arch/aarch64/cpu.S ---- 01_wait_forever/src/_arch/aarch64/cpu.S -+++ 02_runtime_init/src/_arch/aarch64/cpu.S -@@ -7,5 +7,15 @@ - .global _start +diff -uNr 01_wait_forever/Cargo.toml 02_runtime_init/Cargo.toml +--- 01_wait_forever/Cargo.toml ++++ 02_runtime_init/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.1.0" ++version = "0.2.0" + authors = ["Andre Richter "] + edition = "2021" +@@ -21,3 +21,7 @@ + ##-------------------------------------------------------------------------------------------------- + + [dependencies] ++ ++# Platform specific dependencies ++[target.'cfg(target_arch = "aarch64")'.dependencies] ++aarch64-cpu = { version = "9.x.x" } + +diff -uNr 01_wait_forever/Makefile 02_runtime_init/Makefile +--- 01_wait_forever/Makefile ++++ 02_runtime_init/Makefile +@@ -181,6 +181,7 @@ + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ ++ --section .rodata \ + $(KERNEL_ELF) | rustfilt + ##------------------------------------------------------------------------------ + +diff -uNr 01_wait_forever/src/_arch/aarch64/cpu/boot.rs 02_runtime_init/src/_arch/aarch64/cpu/boot.rs +--- 01_wait_forever/src/_arch/aarch64/cpu/boot.rs ++++ 02_runtime_init/src/_arch/aarch64/cpu/boot.rs +@@ -14,4 +14,19 @@ + use core::arch::global_asm; + + // Assembly counterpart to this file. +-global_asm!(include_str!("boot.s")); ++global_asm!( ++ include_str!("boot.s"), ++ CONST_CORE_ID_MASK = const 0b11 ++); ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// The Rust entry of the `kernel` binary. ++/// ++/// The function is called from the assembly `_start` function. ++#[no_mangle] ++pub unsafe fn _start_rust() -> ! { ++ crate::kernel_init() ++} + +diff -uNr 01_wait_forever/src/_arch/aarch64/cpu/boot.s 02_runtime_init/src/_arch/aarch64/cpu/boot.s +--- 01_wait_forever/src/_arch/aarch64/cpu/boot.s ++++ 02_runtime_init/src/_arch/aarch64/cpu/boot.s +@@ -3,6 +3,22 @@ + // Copyright (c) 2021-2023 Andre Richter + + //-------------------------------------------------------------------------------------------------- ++// Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++// Load the address of a symbol into a register, PC-relative. ++// ++// The symbol must lie within +/- 4 GiB of the Program Counter. ++// ++// # Resources ++// ++// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html ++.macro ADR_REL register, symbol ++ adrp \register, \symbol ++ add \register, \register, #:lo12:\symbol ++.endm ++ ++//-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- + .section .text._start +@@ -11,6 +27,34 @@ + // fn _start() + //------------------------------------------------------------------------------ _start: --1: wfe // Wait for event -- b 1b // In case an event happened, jump back to 1 -+ mrs x1, mpidr_el1 // Read Multiprocessor Affinity Register -+ and x1, x1, #3 // Clear all bits except [1:0], which hold core id -+ cbz x1, 2f // Jump to label 2 if we are core 0 -+1: wfe // Wait for event -+ b 1b // In case an event happened, jump back to 1 -+2: // If we are here, we are core0 -+ ldr x1, =_start // Load address of function "_start()" -+ mov sp, x1 // Set start of stack to before our code, aka first -+ // address before "_start()" -+ bl runtime_init // Jump to the "runtime_init()" kernel function -+ b 1b // We should never reach here. But just in case, -+ // park this core aswell - -diff -uNr 01_wait_forever/src/bsp/raspberrypi/link.ld 02_runtime_init/src/bsp/raspberrypi/link.ld ---- 01_wait_forever/src/bsp/raspberrypi/link.ld -+++ 02_runtime_init/src/bsp/raspberrypi/link.ld -@@ -13,5 +13,27 @@ - *(.text._start) *(.text*) - } - -+ .rodata : -+ { -+ *(.rodata*) -+ } ++ // Only proceed on the boot core. Park it otherwise. ++ mrs x0, MPIDR_EL1 ++ and x0, x0, {CONST_CORE_ID_MASK} ++ ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs ++ cmp x0, x1 ++ b.ne .L_parking_loop + -+ .data : -+ { -+ *(.data*) -+ } ++ // If execution reaches here, it is the boot core. + -+ /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ -+ .bss ALIGN(8): -+ { -+ __bss_start = .; -+ *(.bss*); -+ . = ALIGN(8); ++ // Initialize DRAM. ++ ADR_REL x0, __bss_start ++ ADR_REL x1, __bss_end_exclusive + -+ /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ -+ . += 8; -+ __bss_end_inclusive = . - 8; -+ } ++.L_bss_init_loop: ++ cmp x0, x1 ++ b.eq .L_prepare_rust ++ stp xzr, xzr, [x0], #16 ++ b .L_bss_init_loop + - /DISCARD/ : { *(.comment*) } - } ++ // Prepare the jump to Rust code. ++.L_prepare_rust: ++ // Set the stack pointer. ++ ADR_REL x0, __boot_core_stack_end_exclusive ++ mov sp, x0 ++ ++ // Jump to Rust code. ++ b _start_rust ++ + // Infinitely wait for events (aka "park the core"). + .L_parking_loop: + wfe -diff -uNr 01_wait_forever/src/bsp/raspberrypi/memory.rs 02_runtime_init/src/bsp/raspberrypi/memory.rs ---- 01_wait_forever/src/bsp/raspberrypi/memory.rs -+++ 02_runtime_init/src/bsp/raspberrypi/memory.rs -@@ -0,0 +1,37 @@ +diff -uNr 01_wait_forever/src/_arch/aarch64/cpu.rs 02_runtime_init/src/_arch/aarch64/cpu.rs +--- 01_wait_forever/src/_arch/aarch64/cpu.rs ++++ 02_runtime_init/src/_arch/aarch64/cpu.rs +@@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2020 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + -+//! BSP Memory Management. ++//! Architectural processor code. ++//! ++//! # Orientation ++//! ++//! Since arch modules are imported into generic modules using the path attribute, the path of this ++//! file is: ++//! ++//! crate::cpu::arch_cpu + -+use core::{cell::UnsafeCell, ops::RangeInclusive}; ++use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- -+// Private Definitions ++// Public Code +//-------------------------------------------------------------------------------------------------- + -+// Symbols from the linker script. -+extern "Rust" { -+ static __bss_start: UnsafeCell; -+ static __bss_end_inclusive: UnsafeCell; ++/// Pause execution on the core. ++#[inline(always)] ++pub fn wait_forever() -> ! { ++ loop { ++ asm::wfe() ++ } +} + +diff -uNr 01_wait_forever/src/bsp/raspberrypi/cpu.rs 02_runtime_init/src/bsp/raspberrypi/cpu.rs +--- 01_wait_forever/src/bsp/raspberrypi/cpu.rs ++++ 02_runtime_init/src/bsp/raspberrypi/cpu.rs +@@ -0,0 +1,14 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- -+// Public Code ++// Public Definitions +//-------------------------------------------------------------------------------------------------- + -+/// Return the inclusive range spanning the .bss section. -+/// -+/// # Safety -+/// -+/// - Values are provided by the linker script and must be trusted as-is. -+/// - The linker-provided addresses must be u64 aligned. -+pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { -+ let range; -+ unsafe { -+ range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); -+ } -+ assert!(!range.is_empty()); ++/// Used by `arch` code to find the early boot core. ++#[no_mangle] ++#[link_section = ".text._start_arguments"] ++pub static BOOT_CORE_ID: u64 = 0; + +diff -uNr 01_wait_forever/src/bsp/raspberrypi/kernel.ld 02_runtime_init/src/bsp/raspberrypi/kernel.ld +--- 01_wait_forever/src/bsp/raspberrypi/kernel.ld ++++ 02_runtime_init/src/bsp/raspberrypi/kernel.ld +@@ -3,6 +3,8 @@ + * Copyright (c) 2018-2023 Andre Richter + */ + ++__rpi_phys_dram_start_addr = 0; + -+ range -+} + /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ + __rpi_phys_binary_load_addr = 0x80000; + +@@ -13,21 +15,65 @@ + * 4 == R + * 5 == RX + * 6 == RW ++ * ++ * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. ++ * It doesn't mean all of them need actually be loaded. + */ + PHDRS + { +- segment_code PT_LOAD FLAGS(5); ++ segment_boot_core_stack PT_LOAD FLAGS(6); ++ segment_code PT_LOAD FLAGS(5); ++ segment_data PT_LOAD FLAGS(6); + } + + SECTIONS + { +- . = __rpi_phys_binary_load_addr; ++ . = __rpi_phys_dram_start_addr; ++ ++ /*********************************************************************************************** ++ * Boot Core Stack ++ ***********************************************************************************************/ ++ .boot_core_stack (NOLOAD) : ++ { ++ /* ^ */ ++ /* | stack */ ++ . += __rpi_phys_binary_load_addr; /* | growth */ ++ /* | direction */ ++ __boot_core_stack_end_exclusive = .; /* | */ ++ } :segment_boot_core_stack + + /*********************************************************************************************** +- * Code ++ * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) ++ *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ ++ *(.text._start_rust) /* The Rust entry point */ ++ *(.text*) /* Everything else */ + } :segment_code ++ ++ .rodata : ALIGN(8) { *(.rodata*) } :segment_code ++ ++ /*********************************************************************************************** ++ * Data + BSS ++ ***********************************************************************************************/ ++ .data : { *(.data*) } :segment_data ++ ++ /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ ++ .bss (NOLOAD) : ALIGN(16) ++ { ++ __bss_start = .; ++ *(.bss*); ++ . = ALIGN(16); ++ __bss_end_exclusive = .; ++ } :segment_data ++ ++ /*********************************************************************************************** ++ * Misc ++ ***********************************************************************************************/ ++ .got : { *(.got*) } ++ ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") ++ ++ /DISCARD/ : { *(.comment*) } + } diff -uNr 01_wait_forever/src/bsp/raspberrypi.rs 02_runtime_init/src/bsp/raspberrypi.rs --- 01_wait_forever/src/bsp/raspberrypi.rs @@ -127,24 +287,42 @@ diff -uNr 01_wait_forever/src/bsp/raspberrypi.rs 02_runtime_init/src/bsp/raspber //! Top-level BSP file for the Raspberry Pi 3 and 4. -// Coming soon. -+pub mod memory; ++pub mod cpu; + +diff -uNr 01_wait_forever/src/cpu.rs 02_runtime_init/src/cpu.rs +--- 01_wait_forever/src/cpu.rs ++++ 02_runtime_init/src/cpu.rs +@@ -4,4 +4,13 @@ + + //! Processor code. + ++#[cfg(target_arch = "aarch64")] ++#[path = "_arch/aarch64/cpu.rs"] ++mod arch_cpu; ++ + mod boot; ++ ++//-------------------------------------------------------------------------------------------------- ++// Architectural Public Reexports ++//-------------------------------------------------------------------------------------------------- ++pub use arch_cpu::wait_forever; diff -uNr 01_wait_forever/src/main.rs 02_runtime_init/src/main.rs --- 01_wait_forever/src/main.rs +++ 02_runtime_init/src/main.rs -@@ -97,10 +97,20 @@ +@@ -104,7 +104,9 @@ + //! + //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. + //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. ++//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + ++#![feature(asm_const)] #![no_main] #![no_std] --// `mod cpu` provides the `_start()` function, the first function to run. -+// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -+// `runtime_init()`, which jumps to `kernel_init()`. - - mod bsp; +@@ -112,4 +114,11 @@ mod cpu; -+mod memory; mod panic_wait; -+mod runtime_init; -// Kernel code coming next tutorial. +/// Early init code. @@ -156,82 +334,23 @@ diff -uNr 01_wait_forever/src/main.rs 02_runtime_init/src/main.rs + panic!() +} -diff -uNr 01_wait_forever/src/memory.rs 02_runtime_init/src/memory.rs ---- 01_wait_forever/src/memory.rs -+++ 02_runtime_init/src/memory.rs -@@ -0,0 +1,30 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Memory Management. -+ -+use core::ops::RangeInclusive; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Zero out an inclusive memory range. -+/// -+/// # Safety -+/// -+/// - `range.start` and `range.end` must be valid. -+/// - `range.start` and `range.end` must be `T` aligned. -+pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -+where -+ T: From, -+{ -+ let mut ptr = *range.start(); -+ let end_inclusive = *range.end(); -+ -+ while ptr <= end_inclusive { -+ core::ptr::write_volatile(ptr, T::from(0)); -+ ptr = ptr.offset(1); -+ } -+} +diff -uNr 01_wait_forever/src/panic_wait.rs 02_runtime_init/src/panic_wait.rs +--- 01_wait_forever/src/panic_wait.rs ++++ 02_runtime_init/src/panic_wait.rs +@@ -4,6 +4,7 @@ -diff -uNr 01_wait_forever/src/runtime_init.rs 02_runtime_init/src/runtime_init.rs ---- 01_wait_forever/src/runtime_init.rs -+++ 02_runtime_init/src/runtime_init.rs -@@ -0,0 +1,38 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Rust runtime initialization code. -+ -+use crate::{bsp, memory}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Zero out the .bss section. -+/// -+/// # Safety -+/// -+/// - Must only be called pre `kernel_init()`. -+#[inline(always)] -+unsafe fn zero_bss() { -+ memory::zero_volatile(bsp::memory::bss_range_inclusive()); -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -+/// init code. -+/// -+/// # Safety -+/// -+/// - Only a single core must be active and running this function. -+#[no_mangle] -+pub unsafe fn runtime_init() -> ! { -+ zero_bss(); -+ -+ crate::kernel_init() -+} + //! A panic handler that infinitely waits. + ++use crate::cpu; + use core::panic::PanicInfo; + + //-------------------------------------------------------------------------------------------------- +@@ -12,5 +13,5 @@ + + #[panic_handler] + fn panic(_info: &PanicInfo) -> ! { +- unimplemented!() ++ cpu::wait_forever() + } ``` diff --git a/02_runtime_init/build.rs b/02_runtime_init/build.rs index 40ee0284d..cab00bb37 100644 --- a/02_runtime_init/build.rs +++ b/02_runtime_init/build.rs @@ -1,7 +1,20 @@ -use std::env; +use std::{env, fs, process}; fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; - println!("cargo:rerun-if-changed={}", linker_file); + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); } diff --git a/02_runtime_init/src/_arch/aarch64/cpu.S b/02_runtime_init/src/_arch/aarch64/cpu.S deleted file mode 100644 index 3ed5c0613..000000000 --- a/02_runtime_init/src/_arch/aarch64/cpu.S +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -.section ".text._start" - -.global _start - -_start: - mrs x1, mpidr_el1 // Read Multiprocessor Affinity Register - and x1, x1, #3 // Clear all bits except [1:0], which hold core id - cbz x1, 2f // Jump to label 2 if we are core 0 -1: wfe // Wait for event - b 1b // In case an event happened, jump back to 1 -2: // If we are here, we are core0 - ldr x1, =_start // Load address of function "_start()" - mov sp, x1 // Set start of stack to before our code, aka first - // address before "_start()" - bl runtime_init // Jump to the "runtime_init()" kernel function - b 1b // We should never reach here. But just in case, - // park this core aswell diff --git a/02_runtime_init/src/_arch/aarch64/cpu.rs b/02_runtime_init/src/_arch/aarch64/cpu.rs index 1d3e871a6..11d5024e8 100644 --- a/02_runtime_init/src/_arch/aarch64/cpu.rs +++ b/02_runtime_init/src/_arch/aarch64/cpu.rs @@ -1,11 +1,17 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu -// Assembly counterpart to this file. -global_asm!(include_str!("cpu.S")); +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code @@ -14,13 +20,7 @@ global_asm!(include_str!("cpu.S")); /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { - unsafe { - loop { - #[rustfmt::skip] - asm!( - "wfe", - options(nomem, nostack, preserves_flags) - ); - } + loop { + asm::wfe() } } diff --git a/02_runtime_init/src/_arch/aarch64/cpu/boot.rs b/02_runtime_init/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..2a6c46492 --- /dev/null +++ b/02_runtime_init/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff --git a/02_runtime_init/src/_arch/aarch64/cpu/boot.s b/02_runtime_init/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..0011c6074 --- /dev/null +++ b/02_runtime_init/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed on the boot core. Park it otherwise. + mrs x0, MPIDR_EL1 + and x0, x0, {CONST_CORE_ID_MASK} + ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x0, x1 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Jump to Rust code. + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/02_runtime_init/src/bsp.rs b/02_runtime_init/src/bsp.rs index db48385eb..b128add9b 100644 --- a/02_runtime_init/src/bsp.rs +++ b/02_runtime_init/src/bsp.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter -//! Conditional re-exporting of Board Support Packages. +//! Conditional reexporting of Board Support Packages. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; diff --git a/02_runtime_init/src/bsp/raspberrypi.rs b/02_runtime_init/src/bsp/raspberrypi.rs index e4ecbd1d8..c3abe0a69 100644 --- a/02_runtime_init/src/bsp/raspberrypi.rs +++ b/02_runtime_init/src/bsp/raspberrypi.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. -pub mod memory; +pub mod cpu; diff --git a/02_runtime_init/src/bsp/raspberrypi/cpu.rs b/02_runtime_init/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/02_runtime_init/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/02_runtime_init/src/bsp/raspberrypi/kernel.ld b/02_runtime_init/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..f6c188434 --- /dev/null +++ b/02_runtime_init/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/02_runtime_init/src/bsp/raspberrypi/link.ld b/02_runtime_init/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/02_runtime_init/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/02_runtime_init/src/bsp/raspberrypi/memory.rs b/02_runtime_init/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 25ba9f156..000000000 --- a/02_runtime_init/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/02_runtime_init/src/cpu.rs b/02_runtime_init/src/cpu.rs index fd5c9794e..13b89581f 100644 --- a/02_runtime_init/src/cpu.rs +++ b/02_runtime_init/src/cpu.rs @@ -1,10 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; -pub use arch_cpu::*; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::wait_forever; diff --git a/02_runtime_init/src/cpu/boot.rs b/02_runtime_init/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/02_runtime_init/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/02_runtime_init/src/main.rs b/02_runtime_init/src/main.rs index 336824a16..152d7544f 100644 --- a/02_runtime_init/src/main.rs +++ b/02_runtime_init/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] //! The `kernel` binary. //! @@ -20,15 +22,22 @@ //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. //! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! @@ -37,9 +46,8 @@ //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! @@ -91,20 +99,20 @@ //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. -#![feature(asm)] -#![feature(global_asm)] +#![feature(asm_const)] #![no_main] #![no_std] -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - mod bsp; mod cpu; -mod memory; mod panic_wait; -mod runtime_init; /// Early init code. /// diff --git a/02_runtime_init/src/memory.rs b/02_runtime_init/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/02_runtime_init/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/02_runtime_init/src/panic_wait.rs b/02_runtime_init/src/panic_wait.rs index 560a1724e..34a98173f 100644 --- a/02_runtime_init/src/panic_wait.rs +++ b/02_runtime_init/src/panic_wait.rs @@ -1,12 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::cpu; use core::panic::PanicInfo; +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + #[panic_handler] fn panic(_info: &PanicInfo) -> ! { cpu::wait_forever() diff --git a/02_runtime_init/src/runtime_init.rs b/02_runtime_init/src/runtime_init.rs deleted file mode 100644 index 0e3702b47..000000000 --- a/02_runtime_init/src/runtime_init.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -#[no_mangle] -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/03_hacky_hello_world/.vscode/settings.json b/03_hacky_hello_world/.vscode/settings.json index a0d6a9202..bfa278e9a 100644 --- a/03_hacky_hello_world/.vscode/settings.json +++ b/03_hacky_hello_world/.vscode/settings.json @@ -1,7 +1,10 @@ { - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false } diff --git a/03_hacky_hello_world/Cargo.lock b/03_hacky_hello_world/Cargo.lock index 3e9c31110..6e5873dfb 100644 --- a/03_hacky_hello_world/Cargo.lock +++ b/03_hacky_hello_world/Cargo.lock @@ -1,6 +1,25 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + [[package]] -name = "kernel" -version = "0.1.0" +name = "mingo" +version = "0.3.0" +dependencies = [ + "aarch64-cpu", +] +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/03_hacky_hello_world/Cargo.toml b/03_hacky_hello_world/Cargo.toml index 0f798fcbe..a6d527c1a 100644 --- a/03_hacky_hello_world/Cargo.toml +++ b/03_hacky_hello_world/Cargo.toml @@ -1,20 +1,27 @@ [package] -name = "kernel" -version = "0.1.0" +name = "mingo" +version = "0.3.0" authors = ["Andre Richter "] -edition = "2018" +edition = "2021" [profile.release] lto = true -# The features section is used to select the target board. [features] default = [] bsp_rpi3 = [] bsp_rpi4 = [] +[[bin]] +name = "kernel" +path = "src/main.rs" + ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/03_hacky_hello_world/Makefile b/03_hacky_hello_world/Makefile index a9b0f82ce..ce5aff099 100644 --- a/03_hacky_hello_world/Makefile +++ b/03_hacky_hello_world/Makefile @@ -1,11 +1,25 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2020 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -# Default to the RPi3 +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. BSP ?= rpi3 -# BSP-specific arguments + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img @@ -14,7 +28,8 @@ ifeq ($(BSP),rpi3) QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat @@ -24,75 +39,182 @@ else ifeq ($(BSP),rpi4) QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif -# Export for build.rs -export LINKER_FILE +# Export for build.rs. +export LD_SCRIPT_PATH + + -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ + $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary -KERNEL_ELF = target/$(TARGET)/release/kernel +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu clippy clean readelf objdump nm check -all: $(KERNEL_BIN) +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu clippy clean readelf objdump nm check -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) +all: $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ doc: - $(DOC_CMD) --document-private-items --open + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. -ifeq ($(QEMU_MACHINE_TYPE),) qemu: - @echo "This board is not yet supported for QEMU." -else + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/03_hacky_hello_world/README.CN.md b/03_hacky_hello_world/README.CN.md new file mode 100644 index 000000000..ac08fae53 --- /dev/null +++ b/03_hacky_hello_world/README.CN.md @@ -0,0 +1,35 @@ +# 教程 03 - Hacky Hello World + +## tl;dr + +- 介绍全局的`println!()`宏以便尽早启用"printf debugging"。 +- 为了保持教程长度合理,打印函数目前 "滥用" 了 QEMU 属性,该属性允许我们在没有正确设置的情况下使用树莓派的`UART`。 +- 在接下来的教程中将逐步使用真实硬件的`UART`。 + +## 值得注意的补充 + +- `src/console.rs`为控制台命令和通过`console::console()`对内核控制台的全局访问引入了接口`Traits`。 +- `src/bsp/raspberrypi/console.rs` 实现QEMU仿真UART的接口。 +- 紧急处理程序使用新的`println!()`以显示用户错误消息。 +- 有一个新的Makefile目录`make test`,用于自动测试。它在`QEMU`中引导编译后的内核,并检查内核生成的预期输出字符串。 + - 在本教程中,它检查字符串`Stopping here`,该字符串由`panic!()`在`main.rs`的末尾。 + +## 测试一下 + +QEMU不再以汇编模式运行。从现在起,它将显示`console`的输出。 + +```console +$ make qemu +[...] + +Hello from Rust! +Kernel panic! + +Panic location: + File 'src/main.rs', line 126, column 5 + +Stopping here. +``` + +## 相比之前的变化(diff) +请检查[英文版本](README.md#diff-to-previous),这是最新的。 diff --git a/03_hacky_hello_world/README.ES.md b/03_hacky_hello_world/README.ES.md new file mode 100644 index 000000000..eafa3c214 --- /dev/null +++ b/03_hacky_hello_world/README.ES.md @@ -0,0 +1,45 @@ +# Tutorial 03 - Hacky Hello World + +## tl;dr + +* Se añade la macro global `print!()` para habilitar la "depuración basada en printf" ("printf debugging") lo más pronto posible. +* Para mantener una duración razonable en este tutorial, las funciones de impresión por el momento "abusan" una propiedad de QEMU que nos permite hacer uso del `UART` de la Raspberry sin haberla configurado apropiadamente. +* El uso del hardware real de `UART` se habilitará paso por paso en los siguientes tutoriales. + +## Adiciones notables + +* `src/console.rs` introduce una interfaz con `Trait`s para comandos de consola. +* `src/bsp/raspberrypi/console.rs` implementa la interfaz para que QEMU pueda crear una emulación de UART. +* El *panic handler* (manejador de pánico) hace uso de la nueva macro `print!()` para mostrar mensajes de error del usuario. +* Hay un nuevo objetivo en el Makefile: `make test`, destinado a la automatización de pruebas. Este comando inicia el kernel (núcleo) compilado en `QEMU`, y busca una cadena de texto específica en la salida que ha sido producida por el kernel (núcleo). + * En este tutorial, se buscará la cadena `Stopping here`, que es creada por la macro `panic!()` al final del archivo `main.rs`. + +## Pruébalo + +QEMU ya no está siendo ejecutado en modo ensamblador. Desde ahora en adelante mostrará la salida de la `consola`. + +```console +$ make qemu +[...] +Hello from Rust! + +Kernel panic: Stopping here. +``` + +### Diccionario + +* *Hacky:* Solución torpe o poco elegante para un problema. + +* *Debugging:* Proceso para identificar y corregir errores de programación. + + * *printf debugging:* Usado para describir el trabajo de depuración (*debugging*) poniendo comandos que dan una salida en consola, como el de "printf", en diferentes lugares del programa; observando la información y tratando de deducir qué está mal en el programa basándose en la información que nos dan nuestros comandos. + +* *Traits:* Un *trait* le hace saber al compilador de Rust acerca de una funcionalidad que tiene un tipo de dato particular y que puede compartir con otros tipos de datos. + + > NOTA: Los *traits* son similares a una característica que se le conoce comúnmente como *interfaces* en otros lenguajes, aunque con algunas diferencias. + + Si deseas aprender más acerca de esto, por favor lee este capítulo del libro de Rust: [Traits: Defining Shared Behavior - The Rust Programming Language](https://doc.rust-lang.org/book/ch10-02-traits.html) + +## Diferencias con el archivo anterior + +Please check [the english version](README.md#diff-to-previous), which is kept up-to-date. diff --git a/03_hacky_hello_world/README.md b/03_hacky_hello_world/README.md index 4fac48da4..07bf45032 100644 --- a/03_hacky_hello_world/README.md +++ b/03_hacky_hello_world/README.md @@ -2,16 +2,21 @@ ## tl;dr -- Introducing global `print!()` macros to enable "printf debugging" at the earliest. +- Introducing global `println!()` macros to enable "printf debugging" at the earliest. - To keep tutorial length reasonable, printing functions for now "abuse" a QEMU property that lets - us use the RPi's `UART` without setting it up properly. -- Using the real hardware `UART` is enabled step-by-step in following tutorials. + us use the Raspberry's `UART` without setting it up properly. +- Using the real hardware `UART` is enabled step-by-step in following tutorials. ## Notable additions -- `src/console.rs` introduces interface `Traits` for console commands. +- `src/console.rs` introduces interface `Traits` for console commands and global access to the + kernel's console through `console::console()`. - `src/bsp/raspberrypi/console.rs` implements the interface for QEMU's emulated UART. -- The panic handler makes use of the new `print!()` to display user error messages. +- The panic handler makes use of the new `println!()` to display user error messages. +- There is a new Makefile target, `make test`, intended for automated testing. It boots the compiled + kernel in `QEMU`, and checks for an expected output string produced by the kernel. + - In this tutorial, it checks for the string `Stopping here`, which is emitted by the `panic!()` + at the end of `main.rs`. ## Test it @@ -20,18 +25,35 @@ QEMU is no longer running in assembly mode. It will from now on show the output ```console $ make qemu [...] + Hello from Rust! +Kernel panic! + +Panic location: + File 'src/main.rs', line 126, column 5 -Kernel panic: Stopping here. +Stopping here. ``` ## Diff to previous ```diff +diff -uNr 02_runtime_init/Cargo.toml 03_hacky_hello_world/Cargo.toml +--- 02_runtime_init/Cargo.toml ++++ 03_hacky_hello_world/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.2.0" ++version = "0.3.0" + authors = ["Andre Richter "] + edition = "2021" + + diff -uNr 02_runtime_init/Makefile 03_hacky_hello_world/Makefile --- 02_runtime_init/Makefile +++ 03_hacky_hello_world/Makefile -@@ -11,7 +11,7 @@ +@@ -25,7 +25,7 @@ KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 @@ -39,8 +61,8 @@ diff -uNr 02_runtime_init/Makefile 03_hacky_hello_world/Makefile + QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld -@@ -21,7 +21,7 @@ + READELF_BINARY = aarch64-none-elf-readelf +@@ -36,7 +36,7 @@ KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = @@ -48,7 +70,59 @@ diff -uNr 02_runtime_init/Makefile 03_hacky_hello_world/Makefile + QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf +@@ -86,17 +86,20 @@ + --strip-all \ + -O binary + +-EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) ++EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) ++EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb + + ##------------------------------------------------------------------------------ + ## Dockerization + ##------------------------------------------------------------------------------ +-DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +-DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i ++DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial ++DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i ++DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common + + # DOCKER_IMAGE defined in include file (see top of this file). + DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) + DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) ++DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + + + +@@ -191,3 +194,27 @@ + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + ++ ++ ++##-------------------------------------------------------------------------------------------------- ++## Testing targets ++##-------------------------------------------------------------------------------------------------- ++.PHONY: test test_boot ++ ++ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. ++ ++test_boot test: ++ $(call color_header, "$(QEMU_MISSING_STRING)") ++ ++else # QEMU is supported. ++ ++##------------------------------------------------------------------------------ ++## Run boot test ++##------------------------------------------------------------------------------ ++test_boot: $(KERNEL_BIN) ++ $(call color_header, "Boot test - $(BSP)") ++ @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) ++ ++test: test_boot ++ ++endif diff -uNr 02_runtime_init/src/bsp/raspberrypi/console.rs 03_hacky_hello_world/src/bsp/raspberrypi/console.rs --- 02_runtime_init/src/bsp/raspberrypi/console.rs @@ -56,7 +130,7 @@ diff -uNr 02_runtime_init/src/bsp/raspberrypi/console.rs 03_hacky_hello_world/sr @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2020 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! BSP console facilities. + @@ -110,18 +184,20 @@ diff -uNr 02_runtime_init/src/bsp/raspberrypi.rs 03_hacky_hello_world/src/bsp/ra //! Top-level BSP file for the Raspberry Pi 3 and 4. +pub mod console; - pub mod memory; + pub mod cpu; diff -uNr 02_runtime_init/src/console.rs 03_hacky_hello_world/src/console.rs --- 02_runtime_init/src/console.rs +++ 03_hacky_hello_world/src/console.rs -@@ -0,0 +1,19 @@ +@@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2020 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! System console. + ++use crate::bsp; ++ +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- @@ -135,38 +211,44 @@ diff -uNr 02_runtime_init/src/console.rs 03_hacky_hello_world/src/console.rs + /// intention. + pub use core::fmt::Write; +} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Return a reference to the console. ++/// ++/// This is the global console used by all printing macros. ++pub fn console() -> impl interface::Write { ++ bsp::console::console() ++} diff -uNr 02_runtime_init/src/main.rs 03_hacky_hello_world/src/main.rs --- 02_runtime_init/src/main.rs +++ 03_hacky_hello_world/src/main.rs -@@ -93,7 +93,9 @@ - //! - `crate::bsp::memory::*` +@@ -107,12 +107,16 @@ + //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. - #![feature(asm)] + #![feature(asm_const)] +#![feature(format_args_nl)] - #![feature(global_asm)] +#![feature(panic_info_message)] #![no_main] #![no_std] -@@ -101,9 +103,11 @@ - // `runtime_init()`, which jumps to `kernel_init()`. - mod bsp; +mod console; mod cpu; - mod memory; mod panic_wait; +mod print; - mod runtime_init; /// Early init code. -@@ -112,5 +116,7 @@ + /// +@@ -120,5 +124,7 @@ /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { - panic!() -+ println!("[0] Hello from Rust!"); ++ println!("Hello from Rust!"); + + panic!("Stopping here.") } @@ -174,7 +256,7 @@ diff -uNr 02_runtime_init/src/main.rs 03_hacky_hello_world/src/main.rs diff -uNr 02_runtime_init/src/panic_wait.rs 03_hacky_hello_world/src/panic_wait.rs --- 02_runtime_init/src/panic_wait.rs +++ 03_hacky_hello_world/src/panic_wait.rs -@@ -4,10 +4,16 @@ +@@ -4,14 +4,61 @@ //! A panic handler that infinitely waits. @@ -182,14 +264,59 @@ diff -uNr 02_runtime_init/src/panic_wait.rs 03_hacky_hello_world/src/panic_wait. +use crate::{cpu, println}; use core::panic::PanicInfo; + //-------------------------------------------------------------------------------------------------- + // Private Code + //-------------------------------------------------------------------------------------------------- + ++/// Stop immediately if called a second time. ++/// ++/// # Note ++/// ++/// Using atomics here relieves us from needing to use `unsafe` for the static variable. ++/// ++/// On `AArch64`, which is the only implemented architecture at the time of writing this, ++/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store ++/// instructions. They are therefore safe to use even with MMU + caching deactivated. ++/// ++/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load ++/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store ++fn panic_prevent_reenter() { ++ use core::sync::atomic::{AtomicBool, Ordering}; ++ ++ #[cfg(not(target_arch = "aarch64"))] ++ compile_error!("Add the target_arch to above's check if the following code is safe to use"); ++ ++ static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); ++ ++ if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { ++ PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); ++ ++ return; ++ } ++ ++ cpu::wait_forever() ++} ++ #[panic_handler] -fn panic(_info: &PanicInfo) -> ! { +fn panic(info: &PanicInfo) -> ! { -+ if let Some(args) = info.message() { -+ println!("\nKernel panic: {}", args); -+ } else { -+ println!("\nKernel panic!"); -+ } ++ // Protect against panic infinite loops if any of the following code panics itself. ++ panic_prevent_reenter(); ++ ++ let (location, line, column) = match info.location() { ++ Some(loc) => (loc.file(), loc.line(), loc.column()), ++ _ => ("???", 0, 0), ++ }; ++ ++ println!( ++ "Kernel panic!\n\n\ ++ Panic location:\n File '{}', line {}, column {}\n\n\ ++ {}", ++ location, ++ line, ++ column, ++ info.message().unwrap_or(&format_args!("")), ++ ); + cpu::wait_forever() } @@ -200,11 +327,11 @@ diff -uNr 02_runtime_init/src/print.rs 03_hacky_hello_world/src/print.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2020 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + -+//! Printing facilities. ++//! Printing. + -+use crate::{bsp, console}; ++use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- @@ -215,12 +342,12 @@ diff -uNr 02_runtime_init/src/print.rs 03_hacky_hello_world/src/print.rs +pub fn _print(args: fmt::Arguments) { + use console::interface::Write; + -+ bsp::console::console().write_fmt(args).unwrap(); ++ console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// -+/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html ++/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); @@ -228,7 +355,7 @@ diff -uNr 02_runtime_init/src/print.rs 03_hacky_hello_world/src/print.rs + +/// Prints with a newline. +/// -+/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html ++/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); @@ -237,4 +364,12 @@ diff -uNr 02_runtime_init/src/print.rs 03_hacky_hello_world/src/print.rs + }) +} +diff -uNr 02_runtime_init/tests/boot_test_string.rb 03_hacky_hello_world/tests/boot_test_string.rb +--- 02_runtime_init/tests/boot_test_string.rb ++++ 03_hacky_hello_world/tests/boot_test_string.rb +@@ -0,0 +1,3 @@ ++# frozen_string_literal: true ++ ++EXPECTED_PRINT = 'Stopping here' + ``` diff --git a/03_hacky_hello_world/build.rs b/03_hacky_hello_world/build.rs index 40ee0284d..cab00bb37 100644 --- a/03_hacky_hello_world/build.rs +++ b/03_hacky_hello_world/build.rs @@ -1,7 +1,20 @@ -use std::env; +use std::{env, fs, process}; fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; - println!("cargo:rerun-if-changed={}", linker_file); + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); } diff --git a/03_hacky_hello_world/src/_arch/aarch64/cpu.S b/03_hacky_hello_world/src/_arch/aarch64/cpu.S deleted file mode 100644 index 3ed5c0613..000000000 --- a/03_hacky_hello_world/src/_arch/aarch64/cpu.S +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -.section ".text._start" - -.global _start - -_start: - mrs x1, mpidr_el1 // Read Multiprocessor Affinity Register - and x1, x1, #3 // Clear all bits except [1:0], which hold core id - cbz x1, 2f // Jump to label 2 if we are core 0 -1: wfe // Wait for event - b 1b // In case an event happened, jump back to 1 -2: // If we are here, we are core0 - ldr x1, =_start // Load address of function "_start()" - mov sp, x1 // Set start of stack to before our code, aka first - // address before "_start()" - bl runtime_init // Jump to the "runtime_init()" kernel function - b 1b // We should never reach here. But just in case, - // park this core aswell diff --git a/03_hacky_hello_world/src/_arch/aarch64/cpu.rs b/03_hacky_hello_world/src/_arch/aarch64/cpu.rs index 1d3e871a6..11d5024e8 100644 --- a/03_hacky_hello_world/src/_arch/aarch64/cpu.rs +++ b/03_hacky_hello_world/src/_arch/aarch64/cpu.rs @@ -1,11 +1,17 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu -// Assembly counterpart to this file. -global_asm!(include_str!("cpu.S")); +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code @@ -14,13 +20,7 @@ global_asm!(include_str!("cpu.S")); /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { - unsafe { - loop { - #[rustfmt::skip] - asm!( - "wfe", - options(nomem, nostack, preserves_flags) - ); - } + loop { + asm::wfe() } } diff --git a/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.rs b/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..2a6c46492 --- /dev/null +++ b/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff --git a/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.s b/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..0011c6074 --- /dev/null +++ b/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed on the boot core. Park it otherwise. + mrs x0, MPIDR_EL1 + and x0, x0, {CONST_CORE_ID_MASK} + ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x0, x1 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Jump to Rust code. + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/03_hacky_hello_world/src/bsp.rs b/03_hacky_hello_world/src/bsp.rs index db48385eb..b128add9b 100644 --- a/03_hacky_hello_world/src/bsp.rs +++ b/03_hacky_hello_world/src/bsp.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter -//! Conditional re-exporting of Board Support Packages. +//! Conditional reexporting of Board Support Packages. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; diff --git a/03_hacky_hello_world/src/bsp/raspberrypi.rs b/03_hacky_hello_world/src/bsp/raspberrypi.rs index fba4f0a26..919d7e793 100644 --- a/03_hacky_hello_world/src/bsp/raspberrypi.rs +++ b/03_hacky_hello_world/src/bsp/raspberrypi.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod console; -pub mod memory; +pub mod cpu; diff --git a/03_hacky_hello_world/src/bsp/raspberrypi/console.rs b/03_hacky_hello_world/src/bsp/raspberrypi/console.rs index 0b699e62b..49d293703 100644 --- a/03_hacky_hello_world/src/bsp/raspberrypi/console.rs +++ b/03_hacky_hello_world/src/bsp/raspberrypi/console.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP console facilities. diff --git a/03_hacky_hello_world/src/bsp/raspberrypi/cpu.rs b/03_hacky_hello_world/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/03_hacky_hello_world/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/03_hacky_hello_world/src/bsp/raspberrypi/kernel.ld b/03_hacky_hello_world/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..f6c188434 --- /dev/null +++ b/03_hacky_hello_world/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/03_hacky_hello_world/src/bsp/raspberrypi/link.ld b/03_hacky_hello_world/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/03_hacky_hello_world/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/03_hacky_hello_world/src/bsp/raspberrypi/memory.rs b/03_hacky_hello_world/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 25ba9f156..000000000 --- a/03_hacky_hello_world/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/03_hacky_hello_world/src/console.rs b/03_hacky_hello_world/src/console.rs index 3a3b638bb..8b094dda6 100644 --- a/03_hacky_hello_world/src/console.rs +++ b/03_hacky_hello_world/src/console.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +use crate::bsp; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -17,3 +19,14 @@ pub mod interface { /// intention. pub use core::fmt::Write; } + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> impl interface::Write { + bsp::console::console() +} diff --git a/03_hacky_hello_world/src/cpu.rs b/03_hacky_hello_world/src/cpu.rs index fd5c9794e..13b89581f 100644 --- a/03_hacky_hello_world/src/cpu.rs +++ b/03_hacky_hello_world/src/cpu.rs @@ -1,10 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; -pub use arch_cpu::*; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::wait_forever; diff --git a/03_hacky_hello_world/src/cpu/boot.rs b/03_hacky_hello_world/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/03_hacky_hello_world/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/03_hacky_hello_world/src/main.rs b/03_hacky_hello_world/src/main.rs index 8b6f4b252..a38495a2b 100644 --- a/03_hacky_hello_world/src/main.rs +++ b/03_hacky_hello_world/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] //! The `kernel` binary. //! @@ -20,15 +22,22 @@ //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. //! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! @@ -37,9 +46,8 @@ //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! @@ -91,24 +99,24 @@ //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. -#![feature(asm)] +#![feature(asm_const)] #![feature(format_args_nl)] -#![feature(global_asm)] #![feature(panic_info_message)] #![no_main] #![no_std] -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - mod bsp; mod console; mod cpu; -mod memory; mod panic_wait; mod print; -mod runtime_init; /// Early init code. /// @@ -116,7 +124,7 @@ mod runtime_init; /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { - println!("[0] Hello from Rust!"); + println!("Hello from Rust!"); panic!("Stopping here.") } diff --git a/03_hacky_hello_world/src/memory.rs b/03_hacky_hello_world/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/03_hacky_hello_world/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/03_hacky_hello_world/src/panic_wait.rs b/03_hacky_hello_world/src/panic_wait.rs index b4d5bc1ae..5bb0896e4 100644 --- a/03_hacky_hello_world/src/panic_wait.rs +++ b/03_hacky_hello_world/src/panic_wait.rs @@ -1,19 +1,64 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + #[panic_handler] fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - println!("\nKernel panic: {}", args); - } else { - println!("\nKernel panic!"); - } + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); cpu::wait_forever() } diff --git a/03_hacky_hello_world/src/print.rs b/03_hacky_hello_world/src/print.rs index 77ebd8b40..4e8c9b375 100644 --- a/03_hacky_hello_world/src/print.rs +++ b/03_hacky_hello_world/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter -//! Printing facilities. +//! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -15,12 +15,12 @@ use core::fmt; pub fn _print(args: fmt::Arguments) { use console::interface::Write; - bsp::console::console().write_fmt(args).unwrap(); + console::console().write_fmt(args).unwrap(); } /// Prints without a newline. /// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html +/// Carbon copy from #[macro_export] macro_rules! print { ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); @@ -28,7 +28,7 @@ macro_rules! print { /// Prints with a newline. /// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html +/// Carbon copy from #[macro_export] macro_rules! println { () => ($crate::print!("\n")); diff --git a/03_hacky_hello_world/src/runtime_init.rs b/03_hacky_hello_world/src/runtime_init.rs deleted file mode 100644 index 0e3702b47..000000000 --- a/03_hacky_hello_world/src/runtime_init.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -#[no_mangle] -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/03_hacky_hello_world/tests/boot_test_string.rb b/03_hacky_hello_world/tests/boot_test_string.rb new file mode 100644 index 000000000..b0c595368 --- /dev/null +++ b/03_hacky_hello_world/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Stopping here' diff --git a/04_safe_globals/.vscode/settings.json b/04_safe_globals/.vscode/settings.json new file mode 100644 index 000000000..bfa278e9a --- /dev/null +++ b/04_safe_globals/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/04_safe_globals/Cargo.lock b/04_safe_globals/Cargo.lock new file mode 100644 index 000000000..3d196407b --- /dev/null +++ b/04_safe_globals/Cargo.lock @@ -0,0 +1,25 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.4.0" +dependencies = [ + "aarch64-cpu", +] + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/04_safe_globals/Cargo.toml b/04_safe_globals/Cargo.toml new file mode 100644 index 000000000..1d8ee6a79 --- /dev/null +++ b/04_safe_globals/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "mingo" +version = "0.4.0" +authors = ["Andre Richter "] +edition = "2021" + +[profile.release] +lto = true + +[features] +default = [] +bsp_rpi3 = [] +bsp_rpi4 = [] + +[[bin]] +name = "kernel" +path = "src/main.rs" + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/04_safe_globals/Makefile b/04_safe_globals/Makefile new file mode 100644 index 000000000..ce5aff099 --- /dev/null +++ b/04_safe_globals/Makefile @@ -0,0 +1,220 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) +endif + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/04_safe_globals/README.CN.md b/04_safe_globals/README.CN.md new file mode 100644 index 000000000..eb35c006d --- /dev/null +++ b/04_safe_globals/README.CN.md @@ -0,0 +1,50 @@ +# 教程 04 - 全局安全 + +## tl;dr + +- 引入了假的锁。 +- 这是第一次展示原始操作系统同步,并支持安全访问全局数据结构。 + +## Rust中的全局可变 + +当我们引入全局可用的`print!`宏在 [教程03],我门有一点作弊。 调用 +`core::fmt`的`write_fmt()`函数,接受`&mut self`的方法之所以有效, +是因为在每次调用时都会创建一个新的`QEMUOutput`实例。 + +如果我们想保留一些状态,例如关于写入字符数的统计数据, +我们需要创建`QEMUOutput`的一个全局实例 (在Rust中,使用`static`关键字). + +然而`static QEMU_OUTPUT`不允许调用具有`&mut self`的函数。 +为此,我们需要`static mut`,但是调用改变`static mut`状态的函数是不安全的。 +这个是Rust编译器对此的推理,它无法再阻止核心/线程同时改变数据(它是全局的,所以每个人都可以从任何地方引用它,检查程序借用在这里帮不上忙)。 + + +这个问题的解决方案是将全局封装到原始同步中。在我们的例子中,是一个*MUTual EXclusion*原语的变体。 +`Mutex`是`synchronization.rs`中引入的一个特性,并由同一文件中的`NullLock`实现。 +为了使代码更易于教学,它省略了用于防止并发访问的实际体系结构特定逻辑,因为只要内核仅在单个内核上执行并禁用中断,我们就不需要它。 + +`NullLock`侧重于展示Rust内部可变性的核心概念。请务必阅读它。 +我们还建议您阅读这篇关于[Rust的引用类型的精确心智模型]文章 + +如果要将`NullLock`与一些真实的互斥实现进行比较,可以查看 +[spin crate]或者[parking lot crate]。 + +[教程03]: ../03_hacky_hello_world +[内部可变性]: https://doc.rust-lang.org/std/cell/index.html +[Rust的引用类型的精确心智模型]: https://docs.rs/dtolnay/0.0.6/dtolnay/macro._02__reference_types.html +[spin crate]: https://github.com/mvdnes/spin-rs +[parking lot crate]: https://github.com/Amanieu/parking_lot + +## 测试 + +```console +$ make qemu +[...] + +[0] Hello from Rust! +[1] Chars written: 22 +[2] Stopping here. +``` + +## 相比之前的变化(diff) +请检查[英文版本](README.md#diff-to-previous),这是最新的。 diff --git a/04_safe_globals/README.md b/04_safe_globals/README.md new file mode 100644 index 000000000..6418ef5bc --- /dev/null +++ b/04_safe_globals/README.md @@ -0,0 +1,366 @@ +# Tutorial 04 - Safe Globals + +## tl;dr + +- A pseudo-lock is introduced. +- It is a first showcase of OS synchronization primitives and enables safe access to a global data + structure. + +## Mutable globals in Rust + +When we introduced the globally usable `print!` macros in [tutorial 03], we cheated a bit. Calling +`core::fmt`'s `write_fmt()` function, which takes an `&mut self`, was only working because on each +call, a new instance of `QEMUOutput` was created. + +If we would want to preserve some state, e.g. statistics about the number of characters written, we +need to make a single global instance of `QEMUOutput` (in Rust, using the `static` keyword). + +A `static QEMU_OUTPUT`, however, would not allow to call functions taking `&mut self`. For that, we +would need a `static mut`, but calling functions that mutate state on `static mut`s is unsafe. The +Rust compiler's reasoning for this is that it can then not prevent anymore that multiple +cores/threads are mutating the data concurrently (it is a global, so everyone can reference it from +anywhere. The borrow checker can't help here). + +The solution to this problem is to wrap the global into a synchronization primitive. In our case, a +variant of a *MUTual EXclusion* primitive. `Mutex` is introduced as a trait in `synchronization.rs`, +and implemented by the `NullLock` in the same file. In order to make the code lean for teaching +purposes, it leaves out the actual architecture-specific logic for protection against concurrent +access, since we don't need it as long as the kernel only executes on a single core with interrupts +disabled. + +The `NullLock` focuses on showcasing the Rust core concept of [interior mutability]. Make sure to +read up on it. I also recommend to read this article about an [accurate mental model for Rust's +reference types]. + +If you want to compare the `NullLock` to some real-world mutex implementations, you can check out +implemntations in the [spin crate] or the [parking lot crate]. + +[tutorial 03]: ../03_hacky_hello_world +[interior mutability]: https://doc.rust-lang.org/std/cell/index.html +[accurate mental model for Rust's reference types]: https://docs.rs/dtolnay/0.0.6/dtolnay/macro._02__reference_types.html +[spin crate]: https://github.com/mvdnes/spin-rs +[parking lot crate]: https://github.com/Amanieu/parking_lot + +## Test it + +```console +$ make qemu +[...] + +[0] Hello from Rust! +[1] Chars written: 22 +[2] Stopping here. +``` + +## Diff to previous +```diff + +diff -uNr 03_hacky_hello_world/Cargo.toml 04_safe_globals/Cargo.toml +--- 03_hacky_hello_world/Cargo.toml ++++ 04_safe_globals/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.3.0" ++version = "0.4.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi/console.rs 04_safe_globals/src/bsp/raspberrypi/console.rs +--- 03_hacky_hello_world/src/bsp/raspberrypi/console.rs ++++ 04_safe_globals/src/bsp/raspberrypi/console.rs +@@ -4,7 +4,7 @@ + + //! BSP console facilities. + +-use crate::console; ++use crate::{console, synchronization, synchronization::NullLock}; + use core::fmt; + + //-------------------------------------------------------------------------------------------------- +@@ -12,25 +12,64 @@ + //-------------------------------------------------------------------------------------------------- + + /// A mystical, magical device for generating QEMU output out of the void. +-struct QEMUOutput; ++/// ++/// The mutex protected part. ++struct QEMUOutputInner { ++ chars_written: usize, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// The main struct. ++pub struct QEMUOutput { ++ inner: NullLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); + + //-------------------------------------------------------------------------------------------------- + // Private Code + //-------------------------------------------------------------------------------------------------- + ++impl QEMUOutputInner { ++ const fn new() -> QEMUOutputInner { ++ QEMUOutputInner { chars_written: 0 } ++ } ++ ++ /// Send a character. ++ fn write_char(&mut self, c: char) { ++ unsafe { ++ core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); ++ } ++ ++ self.chars_written += 1; ++ } ++} ++ + /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are + /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, + /// we get `write_fmt()` automatically. + /// ++/// The function takes an `&mut self`, so it must be implemented for the inner struct. ++/// + /// See [`src/print.rs`]. + /// + /// [`src/print.rs`]: ../../print/index.html +-impl fmt::Write for QEMUOutput { ++impl fmt::Write for QEMUOutputInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { +- unsafe { +- core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); ++ // Convert newline to carrige return + newline. ++ if c == '\n' { ++ self.write_char('\r') + } ++ ++ self.write_char(c); + } + + Ok(()) +@@ -41,7 +80,39 @@ + // Public Code + //-------------------------------------------------------------------------------------------------- + ++impl QEMUOutput { ++ /// Create a new instance. ++ pub const fn new() -> QEMUOutput { ++ QEMUOutput { ++ inner: NullLock::new(QEMUOutputInner::new()), ++ } ++ } ++} ++ + /// Return a reference to the console. +-pub fn console() -> impl console::interface::Write { +- QEMUOutput {} ++pub fn console() -> &'static dyn console::interface::All { ++ &QEMU_OUTPUT + } ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++use synchronization::interface::Mutex; ++ ++/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to ++/// serialize access. ++impl console::interface::Write for QEMUOutput { ++ fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { ++ // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase ++ // readability. ++ self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) ++ } ++} ++ ++impl console::interface::Statistics for QEMUOutput { ++ fn chars_written(&self) -> usize { ++ self.inner.lock(|inner| inner.chars_written) ++ } ++} ++ ++impl console::interface::All for QEMUOutput {} + +diff -uNr 03_hacky_hello_world/src/console.rs 04_safe_globals/src/console.rs +--- 03_hacky_hello_world/src/console.rs ++++ 04_safe_globals/src/console.rs +@@ -12,12 +12,24 @@ + + /// Console interfaces. + pub mod interface { ++ use core::fmt; ++ + /// Console write functions. +- /// +- /// `core::fmt::Write` is exactly what we need for now. Re-export it here because +- /// implementing `console::Write` gives a better hint to the reader about the +- /// intention. +- pub use core::fmt::Write; ++ pub trait Write { ++ /// Write a Rust format string. ++ fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; ++ } ++ ++ /// Console statistics. ++ pub trait Statistics { ++ /// Return the number of characters written. ++ fn chars_written(&self) -> usize { ++ 0 ++ } ++ } ++ ++ /// Trait alias for a full-fledged console. ++ pub trait All: Write + Statistics {} + } + + //-------------------------------------------------------------------------------------------------- +@@ -27,6 +39,6 @@ + /// Return a reference to the console. + /// + /// This is the global console used by all printing macros. +-pub fn console() -> impl interface::Write { ++pub fn console() -> &'static dyn interface::All { + bsp::console::console() + } + +diff -uNr 03_hacky_hello_world/src/main.rs 04_safe_globals/src/main.rs +--- 03_hacky_hello_world/src/main.rs ++++ 04_safe_globals/src/main.rs +@@ -109,6 +109,7 @@ + #![feature(asm_const)] + #![feature(format_args_nl)] + #![feature(panic_info_message)] ++#![feature(trait_alias)] + #![no_main] + #![no_std] + +@@ -117,6 +118,7 @@ + mod cpu; + mod panic_wait; + mod print; ++mod synchronization; + + /// Early init code. + /// +@@ -124,7 +126,12 @@ + /// + /// - Only a single core must be active and running this function. + unsafe fn kernel_init() -> ! { +- println!("Hello from Rust!"); ++ use console::console; + +- panic!("Stopping here.") ++ println!("[0] Hello from Rust!"); ++ ++ println!("[1] Chars written: {}", console().chars_written()); ++ ++ println!("[2] Stopping here."); ++ cpu::wait_forever() + } + +diff -uNr 03_hacky_hello_world/src/print.rs 04_safe_globals/src/print.rs +--- 03_hacky_hello_world/src/print.rs ++++ 04_safe_globals/src/print.rs +@@ -13,8 +13,6 @@ + + #[doc(hidden)] + pub fn _print(args: fmt::Arguments) { +- use console::interface::Write; +- + console::console().write_fmt(args).unwrap(); + } + + +diff -uNr 03_hacky_hello_world/src/synchronization.rs 04_safe_globals/src/synchronization.rs +--- 03_hacky_hello_world/src/synchronization.rs ++++ 04_safe_globals/src/synchronization.rs +@@ -0,0 +1,77 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Synchronization primitives. ++//! ++//! # Resources ++//! ++//! - ++//! - ++//! - ++ ++use core::cell::UnsafeCell; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Synchronization interfaces. ++pub mod interface { ++ ++ /// Any object implementing this trait guarantees exclusive access to the data wrapped within ++ /// the Mutex for the duration of the provided closure. ++ pub trait Mutex { ++ /// The type of the data that is wrapped by this mutex. ++ type Data; ++ ++ /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. ++ fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; ++ } ++} ++ ++/// A pseudo-lock for teaching purposes. ++/// ++/// In contrast to a real Mutex implementation, does not protect against concurrent access from ++/// other cores to the contained data. This part is preserved for later lessons. ++/// ++/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is ++/// executing single-threaded, aka only running on a single core with interrupts disabled. ++pub struct NullLock ++where ++ T: ?Sized, ++{ ++ data: UnsafeCell, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++unsafe impl Send for NullLock where T: ?Sized + Send {} ++unsafe impl Sync for NullLock where T: ?Sized + Send {} ++ ++impl NullLock { ++ /// Create an instance. ++ pub const fn new(data: T) -> Self { ++ Self { ++ data: UnsafeCell::new(data), ++ } ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++ ++impl interface::Mutex for NullLock { ++ type Data = T; ++ ++ fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { ++ // In a real lock, there would be code encapsulating this line that ensures that this ++ // mutable reference will ever only be given out once at a time. ++ let data = unsafe { &mut *self.data.get() }; ++ ++ f(data) ++ } ++} + +``` diff --git a/04_safe_globals/build.rs b/04_safe_globals/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/04_safe_globals/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/04_safe_globals/src/_arch/aarch64/cpu.rs b/04_safe_globals/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..11d5024e8 --- /dev/null +++ b/04_safe_globals/src/_arch/aarch64/cpu.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff --git a/04_safe_globals/src/_arch/aarch64/cpu/boot.rs b/04_safe_globals/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..2a6c46492 --- /dev/null +++ b/04_safe_globals/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff --git a/04_safe_globals/src/_arch/aarch64/cpu/boot.s b/04_safe_globals/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..0011c6074 --- /dev/null +++ b/04_safe_globals/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed on the boot core. Park it otherwise. + mrs x0, MPIDR_EL1 + and x0, x0, {CONST_CORE_ID_MASK} + ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x0, x1 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Jump to Rust code. + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/04_safe_globals/src/bsp.rs b/04_safe_globals/src/bsp.rs new file mode 100644 index 000000000..b128add9b --- /dev/null +++ b/04_safe_globals/src/bsp.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/04_safe_globals/src/bsp/raspberrypi.rs b/04_safe_globals/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..919d7e793 --- /dev/null +++ b/04_safe_globals/src/bsp/raspberrypi.rs @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod console; +pub mod cpu; diff --git a/04_safe_globals/src/bsp/raspberrypi/console.rs b/04_safe_globals/src/bsp/raspberrypi/console.rs new file mode 100644 index 000000000..753cbcb6f --- /dev/null +++ b/04_safe_globals/src/bsp/raspberrypi/console.rs @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP console facilities. + +use crate::{console, synchronization, synchronization::NullLock}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// A mystical, magical device for generating QEMU output out of the void. +/// +/// The mutex protected part. +struct QEMUOutputInner { + chars_written: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The main struct. +pub struct QEMUOutput { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl QEMUOutputInner { + const fn new() -> QEMUOutputInner { + QEMUOutputInner { chars_written: 0 } + } + + /// Send a character. + fn write_char(&mut self, c: char) { + unsafe { + core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); + } + + self.chars_written += 1; + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for QEMUOutputInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + // Convert newline to carrige return + newline. + if c == '\n' { + self.write_char('\r') + } + + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl QEMUOutput { + /// Create a new instance. + pub const fn new() -> QEMUOutput { + QEMUOutput { + inner: NullLock::new(QEMUOutputInner::new()), + } + } +} + +/// Return a reference to the console. +pub fn console() -> &'static dyn console::interface::All { + &QEMU_OUTPUT +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to +/// serialize access. +impl console::interface::Write for QEMUOutput { + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } +} + +impl console::interface::Statistics for QEMUOutput { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } +} + +impl console::interface::All for QEMUOutput {} diff --git a/04_safe_globals/src/bsp/raspberrypi/cpu.rs b/04_safe_globals/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/04_safe_globals/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/04_safe_globals/src/bsp/raspberrypi/kernel.ld b/04_safe_globals/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..f6c188434 --- /dev/null +++ b/04_safe_globals/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/04_safe_globals/src/console.rs b/04_safe_globals/src/console.rs new file mode 100644 index 000000000..d41c95a16 --- /dev/null +++ b/04_safe_globals/src/console.rs @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + bsp::console::console() +} diff --git a/04_safe_globals/src/cpu.rs b/04_safe_globals/src/cpu.rs new file mode 100644 index 000000000..13b89581f --- /dev/null +++ b/04_safe_globals/src/cpu.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::wait_forever; diff --git a/04_safe_globals/src/cpu/boot.rs b/04_safe_globals/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/04_safe_globals/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/04_safe_globals/src/main.rs b/04_safe_globals/src/main.rs new file mode 100644 index 000000000..4c5a7e0d5 --- /dev/null +++ b/04_safe_globals/src/main.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![feature(asm_const)] +#![feature(format_args_nl)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![no_main] +#![no_std] + +mod bsp; +mod console; +mod cpu; +mod panic_wait; +mod print; +mod synchronization; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +unsafe fn kernel_init() -> ! { + use console::console; + + println!("[0] Hello from Rust!"); + + println!("[1] Chars written: {}", console().chars_written()); + + println!("[2] Stopping here."); + cpu::wait_forever() +} diff --git a/04_safe_globals/src/panic_wait.rs b/04_safe_globals/src/panic_wait.rs new file mode 100644 index 000000000..5bb0896e4 --- /dev/null +++ b/04_safe_globals/src/panic_wait.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + cpu::wait_forever() +} diff --git a/04_safe_globals/src/print.rs b/04_safe_globals/src/print.rs new file mode 100644 index 000000000..6de99572d --- /dev/null +++ b/04_safe_globals/src/print.rs @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} diff --git a/04_safe_globals/src/synchronization.rs b/04_safe_globals/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/04_safe_globals/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/04_safe_globals/tests/boot_test_string.rb b/04_safe_globals/tests/boot_test_string.rb new file mode 100644 index 000000000..b0c595368 --- /dev/null +++ b/04_safe_globals/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Stopping here' diff --git a/04_zero_overhead_abstraction/.vscode/settings.json b/04_zero_overhead_abstraction/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/04_zero_overhead_abstraction/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/04_zero_overhead_abstraction/Cargo.lock b/04_zero_overhead_abstraction/Cargo.lock deleted file mode 100644 index fd6d5c737..000000000 --- a/04_zero_overhead_abstraction/Cargo.lock +++ /dev/null @@ -1,32 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/04_zero_overhead_abstraction/Cargo.toml b/04_zero_overhead_abstraction/Cargo.toml deleted file mode 100644 index 517455433..000000000 --- a/04_zero_overhead_abstraction/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = [] -bsp_rpi4 = [] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/04_zero_overhead_abstraction/Makefile b/04_zero_overhead_abstraction/Makefile deleted file mode 100644 index a9b0f82ce..000000000 --- a/04_zero_overhead_abstraction/Makefile +++ /dev/null @@ -1,98 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu clippy clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -endif - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/04_zero_overhead_abstraction/README.md b/04_zero_overhead_abstraction/README.md deleted file mode 100644 index c7ff8a5f6..000000000 --- a/04_zero_overhead_abstraction/README.md +++ /dev/null @@ -1,255 +0,0 @@ -# Tutorial 04 - Zero Overhead Abstraction - -## tl;dr - -- All hand-written assembly is replaced by Rust code from the [cortex-a] crate, which provides - zero-overhead abstractions and wraps the `unsafe` parts. - -[cortex-a]: https://github.com/rust-embedded/cortex-a - -## Diff to previous -```diff - -diff -uNr 03_hacky_hello_world/Cargo.toml 04_zero_overhead_abstraction/Cargo.toml ---- 03_hacky_hello_world/Cargo.toml -+++ 04_zero_overhead_abstraction/Cargo.toml -@@ -18,3 +18,8 @@ - ##-------------------------------------------------------------------------------------------------- - - [dependencies] -+ -+# Platform specific dependencies -+[target.'cfg(target_arch = "aarch64")'.dependencies] -+cortex-a = { version = "5.x.x" } -+ - -diff -uNr 03_hacky_hello_world/src/_arch/aarch64/cpu/smp.rs 04_zero_overhead_abstraction/src/_arch/aarch64/cpu/smp.rs ---- 03_hacky_hello_world/src/_arch/aarch64/cpu/smp.rs -+++ 04_zero_overhead_abstraction/src/_arch/aarch64/cpu/smp.rs -@@ -0,0 +1,22 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Architectural symmetric multiprocessing. -+ -+use cortex_a::regs::*; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return the executing core's id. -+#[inline(always)] -+pub fn core_id() -> T -+where -+ T: From, -+{ -+ const CORE_MASK: u64 = 0b11; -+ -+ T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -+} - -diff -uNr 03_hacky_hello_world/src/_arch/aarch64/cpu.rs 04_zero_overhead_abstraction/src/_arch/aarch64/cpu.rs ---- 03_hacky_hello_world/src/_arch/aarch64/cpu.rs -+++ 04_zero_overhead_abstraction/src/_arch/aarch64/cpu.rs -@@ -4,8 +4,34 @@ - - //! Architectural processor code. - --// Assembly counterpart to this file. --global_asm!(include_str!("cpu.S")); -+use crate::{bsp, cpu}; -+use cortex_a::{asm, regs::*}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Boot Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// The entry of the `kernel` binary. -+/// -+/// The function must be named `_start`, because the linker is looking for this exact name. -+/// -+/// # Safety -+/// -+/// - Linker script must ensure to place this function at `0x80_000`. -+#[naked] -+#[no_mangle] -+pub unsafe fn _start() -> ! { -+ use crate::runtime_init; -+ -+ // Expect the boot core to start in EL2. -+ if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { -+ SP.set(bsp::memory::boot_core_stack_end() as u64); -+ runtime_init::runtime_init() -+ } else { -+ // If not core0, infinitely wait for events. -+ wait_forever() -+ } -+} - - //-------------------------------------------------------------------------------------------------- - // Public Code -@@ -14,13 +40,7 @@ - /// Pause execution on the core. - #[inline(always)] - pub fn wait_forever() -> ! { -- unsafe { -- loop { -- #[rustfmt::skip] -- asm!( -- "wfe", -- options(nomem, nostack, preserves_flags) -- ); -- } -+ loop { -+ asm::wfe() - } - } - -diff -uNr 03_hacky_hello_world/src/_arch/aarch64/cpu.S 04_zero_overhead_abstraction/src/_arch/aarch64/cpu.S ---- 03_hacky_hello_world/src/_arch/aarch64/cpu.S -+++ 04_zero_overhead_abstraction/src/_arch/aarch64/cpu.S -@@ -1,21 +0,0 @@ --// SPDX-License-Identifier: MIT OR Apache-2.0 --// --// Copyright (c) 2018-2020 Andre Richter -- --.section ".text._start" -- --.global _start -- --_start: -- mrs x1, mpidr_el1 // Read Multiprocessor Affinity Register -- and x1, x1, #3 // Clear all bits except [1:0], which hold core id -- cbz x1, 2f // Jump to label 2 if we are core 0 --1: wfe // Wait for event -- b 1b // In case an event happened, jump back to 1 --2: // If we are here, we are core0 -- ldr x1, =_start // Load address of function "_start()" -- mov sp, x1 // Set start of stack to before our code, aka first -- // address before "_start()" -- bl runtime_init // Jump to the "runtime_init()" kernel function -- b 1b // We should never reach here. But just in case, -- // park this core aswell - -diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi/cpu.rs 04_zero_overhead_abstraction/src/bsp/raspberrypi/cpu.rs ---- 03_hacky_hello_world/src/bsp/raspberrypi/cpu.rs -+++ 04_zero_overhead_abstraction/src/bsp/raspberrypi/cpu.rs -@@ -0,0 +1,12 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! BSP Processor code. -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Used by `arch` code to find the early boot core. -+pub const BOOT_CORE_ID: usize = 0; - -diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi/memory.rs 04_zero_overhead_abstraction/src/bsp/raspberrypi/memory.rs ---- 03_hacky_hello_world/src/bsp/raspberrypi/memory.rs -+++ 04_zero_overhead_abstraction/src/bsp/raspberrypi/memory.rs -@@ -17,9 +17,25 @@ - } - - //-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// The board's memory map. -+#[rustfmt::skip] -+pub(super) mod map { -+ pub const BOOT_CORE_STACK_END: usize = 0x8_0000; -+} -+ -+//-------------------------------------------------------------------------------------------------- - // Public Code - //-------------------------------------------------------------------------------------------------- - -+/// Exclusive end address of the boot core's stack. -+#[inline(always)] -+pub fn boot_core_stack_end() -> usize { -+ map::BOOT_CORE_STACK_END -+} -+ - /// Return the inclusive range spanning the .bss section. - /// - /// # Safety - -diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi.rs 04_zero_overhead_abstraction/src/bsp/raspberrypi.rs ---- 03_hacky_hello_world/src/bsp/raspberrypi.rs -+++ 04_zero_overhead_abstraction/src/bsp/raspberrypi.rs -@@ -5,4 +5,5 @@ - //! Top-level BSP file for the Raspberry Pi 3 and 4. - - pub mod console; -+pub mod cpu; - pub mod memory; - -diff -uNr 03_hacky_hello_world/src/cpu/smp.rs 04_zero_overhead_abstraction/src/cpu/smp.rs ---- 03_hacky_hello_world/src/cpu/smp.rs -+++ 04_zero_overhead_abstraction/src/cpu/smp.rs -@@ -0,0 +1,10 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Symmetric multiprocessing. -+ -+#[cfg(target_arch = "aarch64")] -+#[path = "../_arch/aarch64/cpu/smp.rs"] -+mod arch_cpu_smp; -+pub use arch_cpu_smp::*; - -diff -uNr 03_hacky_hello_world/src/cpu.rs 04_zero_overhead_abstraction/src/cpu.rs ---- 03_hacky_hello_world/src/cpu.rs -+++ 04_zero_overhead_abstraction/src/cpu.rs -@@ -8,3 +8,5 @@ - #[path = "_arch/aarch64/cpu.rs"] - mod arch_cpu; - pub use arch_cpu::*; -+ -+pub mod smp; - -diff -uNr 03_hacky_hello_world/src/main.rs 04_zero_overhead_abstraction/src/main.rs ---- 03_hacky_hello_world/src/main.rs -+++ 04_zero_overhead_abstraction/src/main.rs -@@ -92,9 +92,8 @@ - //! - `crate::memory::*` - //! - `crate::bsp::memory::*` - --#![feature(asm)] - #![feature(format_args_nl)] --#![feature(global_asm)] -+#![feature(naked_functions)] - #![feature(panic_info_message)] - #![no_main] - #![no_std] -@@ -116,7 +115,8 @@ - /// - /// - Only a single core must be active and running this function. - unsafe fn kernel_init() -> ! { -- println!("[0] Hello from Rust!"); -+ println!("[0] Hello from pure Rust!"); - -- panic!("Stopping here.") -+ println!("[1] Stopping here."); -+ cpu::wait_forever() - } - -diff -uNr 03_hacky_hello_world/src/runtime_init.rs 04_zero_overhead_abstraction/src/runtime_init.rs ---- 03_hacky_hello_world/src/runtime_init.rs -+++ 04_zero_overhead_abstraction/src/runtime_init.rs -@@ -30,7 +30,6 @@ - /// # Safety - /// - /// - Only a single core must be active and running this function. --#[no_mangle] - pub unsafe fn runtime_init() -> ! { - zero_bss(); - -``` diff --git a/04_zero_overhead_abstraction/build.rs b/04_zero_overhead_abstraction/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/04_zero_overhead_abstraction/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/04_zero_overhead_abstraction/src/_arch/aarch64/cpu.rs b/04_zero_overhead_abstraction/src/_arch/aarch64/cpu.rs deleted file mode 100644 index d49c8aba0..000000000 --- a/04_zero_overhead_abstraction/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - use crate::runtime_init; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); - runtime_init::runtime_init() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} diff --git a/04_zero_overhead_abstraction/src/_arch/aarch64/cpu/smp.rs b/04_zero_overhead_abstraction/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/04_zero_overhead_abstraction/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/04_zero_overhead_abstraction/src/bsp.rs b/04_zero_overhead_abstraction/src/bsp.rs deleted file mode 100644 index db48385eb..000000000 --- a/04_zero_overhead_abstraction/src/bsp.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/04_zero_overhead_abstraction/src/bsp/raspberrypi.rs b/04_zero_overhead_abstraction/src/bsp/raspberrypi.rs deleted file mode 100644 index 0ad1b2aed..000000000 --- a/04_zero_overhead_abstraction/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod memory; diff --git a/04_zero_overhead_abstraction/src/bsp/raspberrypi/console.rs b/04_zero_overhead_abstraction/src/bsp/raspberrypi/console.rs deleted file mode 100644 index 0b699e62b..000000000 --- a/04_zero_overhead_abstraction/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use crate::console; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// A mystical, magical device for generating QEMU output out of the void. -struct QEMUOutput; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for QEMUOutput { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - unsafe { - core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); - } - } - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the console. -pub fn console() -> impl console::interface::Write { - QEMUOutput {} -} diff --git a/04_zero_overhead_abstraction/src/bsp/raspberrypi/cpu.rs b/04_zero_overhead_abstraction/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/04_zero_overhead_abstraction/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/04_zero_overhead_abstraction/src/bsp/raspberrypi/link.ld b/04_zero_overhead_abstraction/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/04_zero_overhead_abstraction/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/04_zero_overhead_abstraction/src/bsp/raspberrypi/memory.rs b/04_zero_overhead_abstraction/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 51cc958ad..000000000 --- a/04_zero_overhead_abstraction/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/04_zero_overhead_abstraction/src/console.rs b/04_zero_overhead_abstraction/src/console.rs deleted file mode 100644 index 3a3b638bb..000000000 --- a/04_zero_overhead_abstraction/src/console.rs +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - /// Console write functions. - /// - /// `core::fmt::Write` is exactly what we need for now. Re-export it here because - /// implementing `console::Write` gives a better hint to the reader about the - /// intention. - pub use core::fmt::Write; -} diff --git a/04_zero_overhead_abstraction/src/cpu.rs b/04_zero_overhead_abstraction/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/04_zero_overhead_abstraction/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/04_zero_overhead_abstraction/src/cpu/smp.rs b/04_zero_overhead_abstraction/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/04_zero_overhead_abstraction/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/04_zero_overhead_abstraction/src/main.rs b/04_zero_overhead_abstraction/src/main.rs deleted file mode 100644 index da1a257da..000000000 --- a/04_zero_overhead_abstraction/src/main.rs +++ /dev/null @@ -1,122 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![feature(format_args_nl)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod memory; -mod panic_wait; -mod print; -mod runtime_init; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -unsafe fn kernel_init() -> ! { - println!("[0] Hello from pure Rust!"); - - println!("[1] Stopping here."); - cpu::wait_forever() -} diff --git a/04_zero_overhead_abstraction/src/memory.rs b/04_zero_overhead_abstraction/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/04_zero_overhead_abstraction/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/04_zero_overhead_abstraction/src/panic_wait.rs b/04_zero_overhead_abstraction/src/panic_wait.rs deleted file mode 100644 index b4d5bc1ae..000000000 --- a/04_zero_overhead_abstraction/src/panic_wait.rs +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{cpu, println}; -use core::panic::PanicInfo; - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - println!("\nKernel panic: {}", args); - } else { - println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/04_zero_overhead_abstraction/src/print.rs b/04_zero_overhead_abstraction/src/print.rs deleted file mode 100644 index 77ebd8b40..000000000 --- a/04_zero_overhead_abstraction/src/print.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} diff --git a/04_zero_overhead_abstraction/src/runtime_init.rs b/04_zero_overhead_abstraction/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/04_zero_overhead_abstraction/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/05_drivers_gpio_uart/.vscode/settings.json b/05_drivers_gpio_uart/.vscode/settings.json new file mode 100644 index 000000000..bfa278e9a --- /dev/null +++ b/05_drivers_gpio_uart/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/05_drivers_gpio_uart/Cargo.lock b/05_drivers_gpio_uart/Cargo.lock new file mode 100644 index 000000000..4514e8825 --- /dev/null +++ b/05_drivers_gpio_uart/Cargo.lock @@ -0,0 +1,26 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.5.0" +dependencies = [ + "aarch64-cpu", + "tock-registers", +] + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/05_drivers_gpio_uart/Cargo.toml b/05_drivers_gpio_uart/Cargo.toml new file mode 100644 index 000000000..c431e4381 --- /dev/null +++ b/05_drivers_gpio_uart/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "mingo" +version = "0.5.0" +authors = ["Andre Richter "] +edition = "2021" + +[profile.release] +lto = true + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] + +[[bin]] +name = "kernel" +path = "src/main.rs" + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/05_drivers_gpio_uart/Makefile b/05_drivers_gpio_uart/Makefile new file mode 100644 index 000000000..f5135d1ed --- /dev/null +++ b/05_drivers_gpio_uart/Makefile @@ -0,0 +1,239 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINITERM = ruby ../common/serial/miniterm.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DEV = --privileged -v /dev:/dev + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu miniterm clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##----------------------------------------------------------------------------- +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Connect to the target's serial +##------------------------------------------------------------------------------ +miniterm: + @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/05_drivers_gpio_uart/README.CN.md b/05_drivers_gpio_uart/README.CN.md new file mode 100644 index 000000000..7999da7b3 --- /dev/null +++ b/05_drivers_gpio_uart/README.CN.md @@ -0,0 +1,138 @@ +# 教程 05 - 驱动程序: GPIO和UART + +## tl;dr + +- 添加了用于真实`UART`和`GPIO`控制器的驱动程序。 +- **我们将首次能够在真实硬件上运行代码** (请向下滚动查看说明)。 + +## 简介 + +在上一篇教程中,我们启用了全局安全变量,为添加第一个真实设备驱动程序奠定了基础。 +我们放弃了神奇的QEMU控制台,并引入了一个`驱动程序管理器`,允许`BSP`将设备驱动程序注册到`内核`中。 + +## 驱动程序管理器 + +第一步是向内核添加一个`driver subsystem`。相应的代码将位于`src/driver.rs`中。 +该子系统引入了`interface::DeviceDriver`,这是每个设备驱动程序都需要实现的通用特征,并为内核所知。 +在同一文件中实例化的全局`DRIVER_MANAGER`实例(类型为`DriverManager`)作为一个中央实体,可以被调用来管理内核中的所有设备驱动程序。 +例如,通过使用全局可访问的`crate::driver::driver_manager().register_driver(...)`,任何代码都可以注册一个实现了`interface::DeviceDriver`特征的具有静态生命周期的对象。 + +在内核初始化期间,调用`crate::driver::driver_manager().init_drivers(...)`将使驱动程序管理器遍历所有已注册的驱动程序, +并启动它们的初始化,并执行可选的`post-init callback`,该回调可以与驱动程序一起注册。 +例如,此机制用于在`UART`驱动程序初始化后将其切换为主系统控制台的驱动程序。 + +## BSP驱动程序实现 + +在`src/bsp/raspberrypi/driver.rs`中,函数`init()`负责注册`UART`和`GPIO`驱动程序。 +因此,在内核初始化期间,按照以下来自`main.rs`的代码,正确的顺序是: +(i)首先初始化BSP驱动程序子系统,然后(ii)调用`driver_manager()`。 + +```rust +unsafe fn kernel_init() -> ! { + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. +``` + + + +驱动程序本身存储在`src/bsp/device_driver`中,并且可以在不同的`BSP`之间重复使用 +在这些教程中添加的第一个驱动程序是`PL011Uart`驱动程序:它实现了`console::interface::*`特征,并且从现在开始用作主系统控制台。 +第二个驱动程序是`GPIO`驱动程序,它根据需要将`RPii's`的`UART`映射(即将来自`SoC`内部的信号路由到实际的硬件引脚)。 +请注意,`GPIO`驱动程序区分**RPi 3**和**RPi 4**。它们的硬件不同,因此我们必须在软件中进行适配。 + +现在,`BSP`还包含了一个内存映射表,位于`src/bsp/raspberrypi/memory.rs`中。它提供了树莓派的`MMIO`地址, +`BSP`使用这些地址来实例化相应的设备驱动程序,以便驱动程序代码知道在内存中找到设备的寄存器的位置。 + +## SD卡启动 + +由于我们现在有了真实的`UART`输出,我们可以在真实的硬件上运行代码。 +由于前面提到的`GPIO`驱动程序的差异,构建过程在**RPi 3**和**RPi 4**之间有所区别。 +默认情况下,所有的`Makefile`目标都将为**RPi 3**构建。 +为了**RPi 4**构建,需要在每个目标前加上`BSP=rpi4`。例如: + +```console +$ BSP=rpi4 make +$ BSP=rpi4 make doc +``` + +不幸的是,QEMU目前还不支持**RPi 4**,因此`BSP=rpi4 make qemu`无法工作。 + +**准备SD卡的一些步骤在RPi3和RPi4之间有所不同,请在以下操作中小心。** + +### 通用步骤 + +1. 创建一个名为`boot`的`FAT32`分区。 +2. 在SD卡上生成一个名为`config.txt`的文件,并将以下内容写入其中: + +```txt +arm_64bit=1 +init_uart_clock=48000000 +``` +### RPi 3 + +3. 从[Raspberry Pi firmware repo](https://github.com/raspberrypi/firmware/tree/master/boot)中将以下文件复制到SD卡上: + - [bootcode.bin](https://github.com/raspberrypi/firmware/raw/master/boot/bootcode.bin) + - [fixup.dat](https://github.com/raspberrypi/firmware/raw/master/boot/fixup.dat) + - [start.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start.elf) +4. 运行`make`命令。 + +### RPi 4 + +3. 从[Raspberry Pi firmware repo](https://github.com/raspberrypi/firmware/tree/master/boot)中将以下文件复制到SD卡上: + - [fixup4.dat](https://github.com/raspberrypi/firmware/raw/master/boot/fixup4.dat) + - [start4.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start4.elf) + - [bcm2711-rpi-4-b.dtb](https://github.com/raspberrypi/firmware/raw/master/boot/bcm2711-rpi-4-b.dtb) +4. 运行`BSP=rpi4 make`命令。 + + +_**注意**: 如果在您的RPi4上无法正常工作,请尝试将`start4.elf`重命名为`start.elf` (不带4) +并复制到SD卡上。_ + +### 再次通用步骤 + +5. 将`kernel8.img`复制到SD卡上,并将SD卡插入RPi。 +6. 运行`miniterm` target,在主机上打开UART设备: + +```console +$ make miniterm +``` + +> ❗ **注意**: `Miniterm`假设默认的串行设备名称为`/dev/ttyUSB0`。Depending on your +> 根据您的主机操作系统,设备名称可能会有所不同。例如,在`macOS`上,它可能是 +> `/dev/tty.usbserial-0001`之类的。在这种情况下,请明确提供设备名称: + + +```console +$ DEV_SERIAL=/dev/tty.usbserial-0001 make miniterm +``` + +7. 将USB串口连接到主机PC。 + - 请参考[top-level README](../README.md#-usb-serial-output)中的接线图。 + - **注意**: TX(发送)线连接到RX(接收)引脚。 + - 确保您**没有**连接USB串口的电源引脚,只连接RX/TX和GND引脚。 +8. 将RPi连接到(USB)电源线,并观察输出。 + +```console +Miniterm 1.0 + +[MT] ⏳ Waiting for /dev/ttyUSB0 +[MT] ✅ Serial connected +[0] mingo version 0.5.0 +[1] Booting on: Raspberry Pi 3 +[2] Drivers loaded: + 1. BCM PL011 UART + 2. BCM GPIO +[3] Chars written: 117 +[4] Echoing input now +``` + +8. 通过按下ctrl-c退出。 + +## 相比之前的变化(diff) +请检查[英文版本](README.md#diff-to-previous),这是最新的。 diff --git a/05_drivers_gpio_uart/README.md b/05_drivers_gpio_uart/README.md new file mode 100644 index 000000000..5e96d40a0 --- /dev/null +++ b/05_drivers_gpio_uart/README.md @@ -0,0 +1,1668 @@ +# Tutorial 05 - Drivers: GPIO and UART + +## tl;dr + +- Drivers for the real `UART` and the `GPIO` controller are added. +- **For the first time, we will be able to run the code on the real hardware** (scroll down for + instructions). + +## Introduction + +Now that we enabled safe globals in the previous tutorial, the infrastructure is laid for adding the +first real device drivers. We throw out the magic QEMU console and introduce a `driver manager`, +which allows the `BSP` to register device drivers with the `kernel`. + +## Driver Manager + +The first step consists of adding a `driver subsystem` to the kernel. The corresponding code will +live in `src/driver.rs`. The subsystem introduces `interface::DeviceDriver`, a common trait that +every device driver will need to implement and that is known to the kernel. A global +`DRIVER_MANAGER` instance (of type `DriverManager`) that is instantiated in the same file serves as +the central entity that can be called to manage all things device drivers in the kernel. For +example, by using the globally accessible `crate::driver::driver_manager().register_driver(...)`, +any code can can register an object with static lifetime that implements the +`interface::DeviceDriver` trait. + +During kernel init, a call to `crate::driver::driver_manager().init_drivers(...)` will let the +driver manager loop over all registered drivers and kick off their initialization, and also execute +an optional `post-init callback` that can be registered alongside the driver. For example, this +mechanism is used to switch over to the `UART` driver as the main system console after the `UART` +driver has been initialized. + +## BSP Driver Implementation + +In `src/bsp/raspberrypi/driver.rs`, the function `init()` takes care of registering the `UART` and +`GPIO` drivers. It is therefore important that during kernel init, the correct order of (i) first +initializing the BSP driver subsystem, and only then (ii) calling the `driver_manager()` is +followed, like the following excerpt from `main.rs` shows: + +```rust +unsafe fn kernel_init() -> ! { + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. +``` + + + +The drivers themselves are stored in `src/bsp/device_driver`, and can be reused between `BSP`s. The +first driver added in these tutorials is the `PL011Uart` driver: It implements the +`console::interface::*` traits and is from now on used as the main system console. The second driver +is the `GPIO` driver, which pinmuxes (that is, routing signals from inside the `SoC` to actual HW +pins) the RPi's PL011 UART accordingly. Note how the `GPIO` driver differentiates between **RPi 3** +and **RPi 4**. Their HW is different, so we have to account for it in SW. + +The `BSP`s now also contain a memory map in `src/bsp/raspberrypi/memory.rs`. It provides the +Raspberry's `MMIO` addresses which are used by the `BSP` to instantiate the respective device +drivers, so that the driver code knows where to find the device's registers in memory. + +## Boot it from SD card + +Since we have real `UART` output now, we can run the code on the real hardware. Building is +differentiated between the **RPi 3** and the **RPi 4** due to before mentioned differences in the +`GPIO` driver. By default, all `Makefile` targets will build for the **RPi 3**. In order to build +for the the **RPi 4**, prepend `BSP=rpi4` to each target. For example: + +```console +$ BSP=rpi4 make +$ BSP=rpi4 make doc +``` + +Unfortunately, QEMU does not yet support the **RPi 4**, so `BSP=rpi4 make qemu` won't work. + +**Some steps for preparing the SD card differ between RPi 3 and RPi 4, so be careful in the +following.** + +### Common for both + +1. Make a single `FAT32` partition named `boot`. +2. On the card, generate a file named `config.txt` with the following contents: + +```txt +arm_64bit=1 +init_uart_clock=48000000 +``` +### RPi 3 + +3. Copy the following files from the [Raspberry Pi firmware repo](https://github.com/raspberrypi/firmware/tree/master/boot) onto the SD card: + - [bootcode.bin](https://github.com/raspberrypi/firmware/raw/master/boot/bootcode.bin) + - [fixup.dat](https://github.com/raspberrypi/firmware/raw/master/boot/fixup.dat) + - [start.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start.elf) +4. Run `make`. + +### RPi 4 + +3. Copy the following files from the [Raspberry Pi firmware repo](https://github.com/raspberrypi/firmware/tree/master/boot) onto the SD card: + - [fixup4.dat](https://github.com/raspberrypi/firmware/raw/master/boot/fixup4.dat) + - [start4.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start4.elf) + - [bcm2711-rpi-4-b.dtb](https://github.com/raspberrypi/firmware/raw/master/boot/bcm2711-rpi-4-b.dtb) +4. Run `BSP=rpi4 make`. + + +_**Note**: Should it not work on your RPi 4, try renaming `start4.elf` to `start.elf` (without the 4) +on the SD card._ + +### Common again + +5. Copy the `kernel8.img` onto the SD card and insert it back into the RPi. +6. Run the `miniterm` target, which opens the UART device on the host: + +```console +$ make miniterm +``` + +> ❗ **NOTE**: `Miniterm` assumes a default serial device name of `/dev/ttyUSB0`. Depending on your +> host operating system, the device name might differ. For example, on `macOS`, it might be +> something like `/dev/tty.usbserial-0001`. In this case, please give the name explicitly: + + +```console +$ DEV_SERIAL=/dev/tty.usbserial-0001 make miniterm +``` + +7. Connect the USB serial to your host PC. + - Wiring diagram at [top-level README](../README.md#-usb-serial-output). + - **NOTE**: TX (transmit) wire connects to the RX (receive) pin. + - Make sure that you **DID NOT** connect the power pin of the USB serial. Only RX/TX and GND. +8. Connect the RPi to the (USB) power cable and observe the output: + +```console +Miniterm 1.0 + +[MT] ⏳ Waiting for /dev/ttyUSB0 +[MT] ✅ Serial connected +[0] mingo version 0.5.0 +[1] Booting on: Raspberry Pi 3 +[2] Drivers loaded: + 1. BCM PL011 UART + 2. BCM GPIO +[3] Chars written: 117 +[4] Echoing input now +``` + +8. Exit by pressing ctrl-c. + +## Diff to previous +```diff + +diff -uNr 04_safe_globals/Cargo.toml 05_drivers_gpio_uart/Cargo.toml +--- 04_safe_globals/Cargo.toml ++++ 05_drivers_gpio_uart/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.4.0" ++version = "0.5.0" + authors = ["Andre Richter "] + edition = "2021" + +@@ -9,8 +9,8 @@ + + [features] + default = [] +-bsp_rpi3 = [] +-bsp_rpi4 = [] ++bsp_rpi3 = ["tock-registers"] ++bsp_rpi4 = ["tock-registers"] + + [[bin]] + name = "kernel" +@@ -22,6 +22,9 @@ + + [dependencies] + ++# Optional dependencies ++tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } ++ + # Platform specific dependencies + [target.'cfg(target_arch = "aarch64")'.dependencies] + aarch64-cpu = { version = "9.x.x" } + +diff -uNr 04_safe_globals/Makefile 05_drivers_gpio_uart/Makefile +--- 04_safe_globals/Makefile ++++ 05_drivers_gpio_uart/Makefile +@@ -13,6 +13,9 @@ + # Default to the RPi3. + BSP ?= rpi3 + ++# Default to a serial device name that is common in Linux. ++DEV_SERIAL ?= /dev/ttyUSB0 ++ + + + ##-------------------------------------------------------------------------------------------------- +@@ -88,6 +91,7 @@ + + EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) + EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb ++EXEC_MINITERM = ruby ../common/serial/miniterm.rb + + ##------------------------------------------------------------------------------ + ## Dockerization +@@ -95,18 +99,26 @@ + DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial + DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i + DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common ++DOCKER_ARG_DEV = --privileged -v /dev:/dev + + # DOCKER_IMAGE defined in include file (see top of this file). + DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) + DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) + DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + ++# Dockerize commands, which require USB device passthrough, only on Linux. ++ifeq ($(shell uname -s),Linux) ++ DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) ++ ++ DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) ++endif ++ + + + ##-------------------------------------------------------------------------------------------------- + ## Targets + ##-------------------------------------------------------------------------------------------------- +-.PHONY: all doc qemu clippy clean readelf objdump nm check ++.PHONY: all doc qemu miniterm clippy clean readelf objdump nm check + + all: $(KERNEL_BIN) + +@@ -156,9 +168,16 @@ + qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) ++ + endif + + ##------------------------------------------------------------------------------ ++## Connect to the target's serial ++##------------------------------------------------------------------------------ ++miniterm: ++ @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) ++ ++##------------------------------------------------------------------------------ + ## Run clippy + ##------------------------------------------------------------------------------ + clippy: + +diff -uNr 04_safe_globals/src/_arch/aarch64/cpu.rs 05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs +--- 04_safe_globals/src/_arch/aarch64/cpu.rs ++++ 05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs +@@ -17,6 +17,17 @@ + // Public Code + //-------------------------------------------------------------------------------------------------- + ++pub use asm::nop; ++ ++/// Spin for `n` cycles. ++#[cfg(feature = "bsp_rpi3")] ++#[inline(always)] ++pub fn spin_for_cycles(n: usize) { ++ for _ in 0..n { ++ asm::nop(); ++ } ++} ++ + /// Pause execution on the core. + #[inline(always)] + pub fn wait_forever() -> ! { + +diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +--- 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ++++ 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +@@ -0,0 +1,228 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! GPIO Driver. ++ ++use crate::{ ++ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, ++ synchronization::NullLock, ++}; ++use tock_registers::{ ++ interfaces::{ReadWriteable, Writeable}, ++ register_bitfields, register_structs, ++ registers::ReadWrite, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++// GPIO registers. ++// ++// Descriptions taken from ++// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf ++// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf ++register_bitfields! { ++ u32, ++ ++ /// GPIO Function Select 1 ++ GPFSEL1 [ ++ /// Pin 15 ++ FSEL15 OFFSET(15) NUMBITS(3) [ ++ Input = 0b000, ++ Output = 0b001, ++ AltFunc0 = 0b100 // PL011 UART RX ++ ++ ], ++ ++ /// Pin 14 ++ FSEL14 OFFSET(12) NUMBITS(3) [ ++ Input = 0b000, ++ Output = 0b001, ++ AltFunc0 = 0b100 // PL011 UART TX ++ ] ++ ], ++ ++ /// GPIO Pull-up/down Register ++ /// ++ /// BCM2837 only. ++ GPPUD [ ++ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. ++ PUD OFFSET(0) NUMBITS(2) [ ++ Off = 0b00, ++ PullDown = 0b01, ++ PullUp = 0b10 ++ ] ++ ], ++ ++ /// GPIO Pull-up/down Clock Register 0 ++ /// ++ /// BCM2837 only. ++ GPPUDCLK0 [ ++ /// Pin 15 ++ PUDCLK15 OFFSET(15) NUMBITS(1) [ ++ NoEffect = 0, ++ AssertClock = 1 ++ ], ++ ++ /// Pin 14 ++ PUDCLK14 OFFSET(14) NUMBITS(1) [ ++ NoEffect = 0, ++ AssertClock = 1 ++ ] ++ ], ++ ++ /// GPIO Pull-up / Pull-down Register 0 ++ /// ++ /// BCM2711 only. ++ GPIO_PUP_PDN_CNTRL_REG0 [ ++ /// Pin 15 ++ GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ ++ NoResistor = 0b00, ++ PullUp = 0b01 ++ ], ++ ++ /// Pin 14 ++ GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ ++ NoResistor = 0b00, ++ PullUp = 0b01 ++ ] ++ ] ++} ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ RegisterBlock { ++ (0x00 => _reserved1), ++ (0x04 => GPFSEL1: ReadWrite), ++ (0x08 => _reserved2), ++ (0x94 => GPPUD: ReadWrite), ++ (0x98 => GPPUDCLK0: ReadWrite), ++ (0x9C => _reserved3), ++ (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), ++ (0xE8 => @END), ++ } ++} ++ ++/// Abstraction for the associated MMIO registers. ++type Registers = MMIODerefWrapper; ++ ++struct GPIOInner { ++ registers: Registers, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Representation of the GPIO HW. ++pub struct GPIO { ++ inner: NullLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl GPIOInner { ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ Self { ++ registers: Registers::new(mmio_start_addr), ++ } ++ } ++ ++ /// Disable pull-up/down on pins 14 and 15. ++ #[cfg(feature = "bsp_rpi3")] ++ fn disable_pud_14_15_bcm2837(&mut self) { ++ use crate::cpu; ++ ++ // Make an educated guess for a good delay value (Sequence described in the BCM2837 ++ // peripherals PDF). ++ // ++ // - According to Wikipedia, the fastest RPi4 clocks around 1.5 GHz. ++ // - The Linux 2837 GPIO driver waits 1 µs between the steps. ++ // ++ // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs ++ // would the CPU be clocked at 2 GHz. ++ const DELAY: usize = 2000; ++ ++ self.registers.GPPUD.write(GPPUD::PUD::Off); ++ cpu::spin_for_cycles(DELAY); ++ ++ self.registers ++ .GPPUDCLK0 ++ .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); ++ cpu::spin_for_cycles(DELAY); ++ ++ self.registers.GPPUD.write(GPPUD::PUD::Off); ++ self.registers.GPPUDCLK0.set(0); ++ } ++ ++ /// Disable pull-up/down on pins 14 and 15. ++ #[cfg(feature = "bsp_rpi4")] ++ fn disable_pud_14_15_bcm2711(&mut self) { ++ self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( ++ GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp ++ + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ++ ); ++ } ++ ++ /// Map PL011 UART as standard output. ++ /// ++ /// TX to pin 14 ++ /// RX to pin 15 ++ pub fn map_pl011_uart(&mut self) { ++ // Select the UART on pins 14 and 15. ++ self.registers ++ .GPFSEL1 ++ .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); ++ ++ // Disable pull-up/down on pins 14 and 15. ++ #[cfg(feature = "bsp_rpi3")] ++ self.disable_pud_14_15_bcm2837(); ++ ++ #[cfg(feature = "bsp_rpi4")] ++ self.disable_pud_14_15_bcm2711(); ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl GPIO { ++ pub const COMPATIBLE: &'static str = "BCM GPIO"; ++ ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ Self { ++ inner: NullLock::new(GPIOInner::new(mmio_start_addr)), ++ } ++ } ++ ++ /// Concurrency safe version of `GPIOInner.map_pl011_uart()` ++ pub fn map_pl011_uart(&self) { ++ self.inner.lock(|inner| inner.map_pl011_uart()) ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++use synchronization::interface::Mutex; ++ ++impl driver::interface::DeviceDriver for GPIO { ++ fn compatible(&self) -> &'static str { ++ Self::COMPATIBLE ++ } ++} + +diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +--- 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ++++ 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +@@ -0,0 +1,407 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! PL011 UART driver. ++//! ++//! # Resources ++//! ++//! - ++//! - ++ ++use crate::{ ++ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, ++ synchronization::NullLock, ++}; ++use core::fmt; ++use tock_registers::{ ++ interfaces::{Readable, Writeable}, ++ register_bitfields, register_structs, ++ registers::{ReadOnly, ReadWrite, WriteOnly}, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++// PL011 UART registers. ++// ++// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. ++register_bitfields! { ++ u32, ++ ++ /// Flag Register. ++ FR [ ++ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the ++ /// Line Control Register, LCR_H. ++ /// ++ /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. ++ /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. ++ /// - This bit does not indicate if there is data in the transmit shift register. ++ TXFE OFFSET(7) NUMBITS(1) [], ++ ++ /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the ++ /// LCR_H Register. ++ /// ++ /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. ++ /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. ++ TXFF OFFSET(5) NUMBITS(1) [], ++ ++ /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the ++ /// LCR_H Register. ++ /// ++ /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. ++ /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. ++ RXFE OFFSET(4) NUMBITS(1) [], ++ ++ /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains ++ /// set until the complete byte, including all the stop bits, has been sent from the shift ++ /// register. ++ /// ++ /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether ++ /// the UART is enabled or not. ++ BUSY OFFSET(3) NUMBITS(1) [] ++ ], ++ ++ /// Integer Baud Rate Divisor. ++ IBRD [ ++ /// The integer baud rate divisor. ++ BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ++ ], ++ ++ /// Fractional Baud Rate Divisor. ++ FBRD [ ++ /// The fractional baud rate divisor. ++ BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ++ ], ++ ++ /// Line Control Register. ++ LCR_H [ ++ /// Word length. These bits indicate the number of data bits transmitted or received in a ++ /// frame. ++ #[allow(clippy::enum_variant_names)] ++ WLEN OFFSET(5) NUMBITS(2) [ ++ FiveBit = 0b00, ++ SixBit = 0b01, ++ SevenBit = 0b10, ++ EightBit = 0b11 ++ ], ++ ++ /// Enable FIFOs: ++ /// ++ /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding ++ /// registers. ++ /// ++ /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). ++ FEN OFFSET(4) NUMBITS(1) [ ++ FifosDisabled = 0, ++ FifosEnabled = 1 ++ ] ++ ], ++ ++ /// Control Register. ++ CR [ ++ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. ++ /// Data reception occurs for either UART signals or SIR signals depending on the setting of ++ /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the ++ /// current character before stopping. ++ RXE OFFSET(9) NUMBITS(1) [ ++ Disabled = 0, ++ Enabled = 1 ++ ], ++ ++ /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. ++ /// Data transmission occurs for either UART signals, or SIR signals depending on the ++ /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it ++ /// completes the current character before stopping. ++ TXE OFFSET(8) NUMBITS(1) [ ++ Disabled = 0, ++ Enabled = 1 ++ ], ++ ++ /// UART enable: ++ /// ++ /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or ++ /// reception, it completes the current character before stopping. ++ /// ++ /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals ++ /// or SIR signals depending on the setting of the SIREN bit ++ UARTEN OFFSET(0) NUMBITS(1) [ ++ /// If the UART is disabled in the middle of transmission or reception, it completes the ++ /// current character before stopping. ++ Disabled = 0, ++ Enabled = 1 ++ ] ++ ], ++ ++ /// Interrupt Clear Register. ++ ICR [ ++ /// Meta field for all pending interrupts. ++ ALL OFFSET(0) NUMBITS(11) [] ++ ] ++} ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ pub RegisterBlock { ++ (0x00 => DR: ReadWrite), ++ (0x04 => _reserved1), ++ (0x18 => FR: ReadOnly), ++ (0x1c => _reserved2), ++ (0x24 => IBRD: WriteOnly), ++ (0x28 => FBRD: WriteOnly), ++ (0x2c => LCR_H: WriteOnly), ++ (0x30 => CR: WriteOnly), ++ (0x34 => _reserved3), ++ (0x44 => ICR: WriteOnly), ++ (0x48 => @END), ++ } ++} ++ ++/// Abstraction for the associated MMIO registers. ++type Registers = MMIODerefWrapper; ++ ++#[derive(PartialEq)] ++enum BlockingMode { ++ Blocking, ++ NonBlocking, ++} ++ ++struct PL011UartInner { ++ registers: Registers, ++ chars_written: usize, ++ chars_read: usize, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Representation of the UART. ++pub struct PL011Uart { ++ inner: NullLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl PL011UartInner { ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ Self { ++ registers: Registers::new(mmio_start_addr), ++ chars_written: 0, ++ chars_read: 0, ++ } ++ } ++ ++ /// Set up baud rate and characteristics. ++ /// ++ /// This results in 8N1 and 921_600 baud. ++ /// ++ /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): ++ /// `(48_000_000 / 16) / 921_600 = 3.2552083`. ++ /// ++ /// This means the integer part is `3` and goes into the `IBRD`. ++ /// The fractional part is `0.2552083`. ++ /// ++ /// `FBRD` calculation according to the PL011 Technical Reference Manual: ++ /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. ++ /// ++ /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a ++ /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. ++ /// ++ /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16modulo`. ++ pub fn init(&mut self) { ++ // Execution can arrive here while there are still characters queued in the TX FIFO and ++ // actively being sent out by the UART hardware. If the UART is turned off in this case, ++ // those queued characters would be lost. ++ // ++ // For example, this can happen during runtime on a call to panic!(), because panic!() ++ // initializes its own UART instance and calls init(). ++ // ++ // Hence, flush first to ensure all pending characters are transmitted. ++ self.flush(); ++ ++ // Turn the UART off temporarily. ++ self.registers.CR.set(0); ++ ++ // Clear all pending interrupts. ++ self.registers.ICR.write(ICR::ALL::CLEAR); ++ ++ // From the PL011 Technical Reference Manual: ++ // ++ // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is ++ // updated on a single write strobe generated by a LCR_H write. So, to internally update the ++ // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. ++ // ++ // Set the baud rate, 8N1 and FIFO enabled. ++ self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); ++ self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); ++ self.registers ++ .LCR_H ++ .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); ++ ++ // Turn the UART on. ++ self.registers ++ .CR ++ .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); ++ } ++ ++ /// Send a character. ++ fn write_char(&mut self, c: char) { ++ // Spin while TX FIFO full is set, waiting for an empty slot. ++ while self.registers.FR.matches_all(FR::TXFF::SET) { ++ cpu::nop(); ++ } ++ ++ // Write the character to the buffer. ++ self.registers.DR.set(c as u32); ++ ++ self.chars_written += 1; ++ } ++ ++ /// Block execution until the last buffered character has been physically put on the TX wire. ++ fn flush(&self) { ++ // Spin until the busy bit is cleared. ++ while self.registers.FR.matches_all(FR::BUSY::SET) { ++ cpu::nop(); ++ } ++ } ++ ++ /// Retrieve a character. ++ fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { ++ // If RX FIFO is empty, ++ if self.registers.FR.matches_all(FR::RXFE::SET) { ++ // immediately return in non-blocking mode. ++ if blocking_mode == BlockingMode::NonBlocking { ++ return None; ++ } ++ ++ // Otherwise, wait until a char was received. ++ while self.registers.FR.matches_all(FR::RXFE::SET) { ++ cpu::nop(); ++ } ++ } ++ ++ // Read one character. ++ let mut ret = self.registers.DR.get() as u8 as char; ++ ++ // Convert carrige return to newline. ++ if ret == '\r' { ++ ret = '\n' ++ } ++ ++ // Update statistics. ++ self.chars_read += 1; ++ ++ Some(ret) ++ } ++} ++ ++/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are ++/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, ++/// we get `write_fmt()` automatically. ++/// ++/// The function takes an `&mut self`, so it must be implemented for the inner struct. ++/// ++/// See [`src/print.rs`]. ++/// ++/// [`src/print.rs`]: ../../print/index.html ++impl fmt::Write for PL011UartInner { ++ fn write_str(&mut self, s: &str) -> fmt::Result { ++ for c in s.chars() { ++ self.write_char(c); ++ } ++ ++ Ok(()) ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl PL011Uart { ++ pub const COMPATIBLE: &'static str = "BCM PL011 UART"; ++ ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ Self { ++ inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), ++ } ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++use synchronization::interface::Mutex; ++ ++impl driver::interface::DeviceDriver for PL011Uart { ++ fn compatible(&self) -> &'static str { ++ Self::COMPATIBLE ++ } ++ ++ unsafe fn init(&self) -> Result<(), &'static str> { ++ self.inner.lock(|inner| inner.init()); ++ ++ Ok(()) ++ } ++} ++ ++impl console::interface::Write for PL011Uart { ++ /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to ++ /// serialize access. ++ fn write_char(&self, c: char) { ++ self.inner.lock(|inner| inner.write_char(c)); ++ } ++ ++ fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { ++ // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase ++ // readability. ++ self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) ++ } ++ ++ fn flush(&self) { ++ // Spin until TX FIFO empty is set. ++ self.inner.lock(|inner| inner.flush()); ++ } ++} ++ ++impl console::interface::Read for PL011Uart { ++ fn read_char(&self) -> char { ++ self.inner ++ .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) ++ } ++ ++ fn clear_rx(&self) { ++ // Read from the RX FIFO until it is indicating empty. ++ while self ++ .inner ++ .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) ++ .is_some() ++ {} ++ } ++} ++ ++impl console::interface::Statistics for PL011Uart { ++ fn chars_written(&self) -> usize { ++ self.inner.lock(|inner| inner.chars_written) ++ } ++ ++ fn chars_read(&self) -> usize { ++ self.inner.lock(|inner| inner.chars_read) ++ } ++} ++ ++impl console::interface::All for PL011Uart {} + +diff -uNr 04_safe_globals/src/bsp/device_driver/bcm.rs 05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs +--- 04_safe_globals/src/bsp/device_driver/bcm.rs ++++ 05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs +@@ -0,0 +1,11 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! BCM driver top level. ++ ++mod bcm2xxx_gpio; ++mod bcm2xxx_pl011_uart; ++ ++pub use bcm2xxx_gpio::*; ++pub use bcm2xxx_pl011_uart::*; + +diff -uNr 04_safe_globals/src/bsp/device_driver/common.rs 05_drivers_gpio_uart/src/bsp/device_driver/common.rs +--- 04_safe_globals/src/bsp/device_driver/common.rs ++++ 05_drivers_gpio_uart/src/bsp/device_driver/common.rs +@@ -0,0 +1,38 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Common device driver code. ++ ++use core::{marker::PhantomData, ops}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++pub struct MMIODerefWrapper { ++ start_addr: usize, ++ phantom: PhantomData T>, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl MMIODerefWrapper { ++ /// Create an instance. ++ pub const unsafe fn new(start_addr: usize) -> Self { ++ Self { ++ start_addr, ++ phantom: PhantomData, ++ } ++ } ++} ++ ++impl ops::Deref for MMIODerefWrapper { ++ type Target = T; ++ ++ fn deref(&self) -> &Self::Target { ++ unsafe { &*(self.start_addr as *const _) } ++ } ++} + +diff -uNr 04_safe_globals/src/bsp/device_driver.rs 05_drivers_gpio_uart/src/bsp/device_driver.rs +--- 04_safe_globals/src/bsp/device_driver.rs ++++ 05_drivers_gpio_uart/src/bsp/device_driver.rs +@@ -0,0 +1,12 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Device driver. ++ ++#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] ++mod bcm; ++mod common; ++ ++#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] ++pub use bcm::*; + +diff -uNr 04_safe_globals/src/bsp/raspberrypi/console.rs 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs +--- 04_safe_globals/src/bsp/raspberrypi/console.rs ++++ 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs +@@ -4,115 +4,13 @@ + + //! BSP console facilities. + +-use crate::{console, synchronization, synchronization::NullLock}; +-use core::fmt; +- +-//-------------------------------------------------------------------------------------------------- +-// Private Definitions +-//-------------------------------------------------------------------------------------------------- +- +-/// A mystical, magical device for generating QEMU output out of the void. +-/// +-/// The mutex protected part. +-struct QEMUOutputInner { +- chars_written: usize, +-} +- +-//-------------------------------------------------------------------------------------------------- +-// Public Definitions +-//-------------------------------------------------------------------------------------------------- +- +-/// The main struct. +-pub struct QEMUOutput { +- inner: NullLock, +-} +- +-//-------------------------------------------------------------------------------------------------- +-// Global instances +-//-------------------------------------------------------------------------------------------------- +- +-static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); +- +-//-------------------------------------------------------------------------------------------------- +-// Private Code +-//-------------------------------------------------------------------------------------------------- +- +-impl QEMUOutputInner { +- const fn new() -> QEMUOutputInner { +- QEMUOutputInner { chars_written: 0 } +- } +- +- /// Send a character. +- fn write_char(&mut self, c: char) { +- unsafe { +- core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); +- } +- +- self.chars_written += 1; +- } +-} +- +-/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +-/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +-/// we get `write_fmt()` automatically. +-/// +-/// The function takes an `&mut self`, so it must be implemented for the inner struct. +-/// +-/// See [`src/print.rs`]. +-/// +-/// [`src/print.rs`]: ../../print/index.html +-impl fmt::Write for QEMUOutputInner { +- fn write_str(&mut self, s: &str) -> fmt::Result { +- for c in s.chars() { +- // Convert newline to carrige return + newline. +- if c == '\n' { +- self.write_char('\r') +- } +- +- self.write_char(c); +- } +- +- Ok(()) +- } +-} ++use crate::console; + + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- + +-impl QEMUOutput { +- /// Create a new instance. +- pub const fn new() -> QEMUOutput { +- QEMUOutput { +- inner: NullLock::new(QEMUOutputInner::new()), +- } +- } +-} +- + /// Return a reference to the console. + pub fn console() -> &'static dyn console::interface::All { +- &QEMU_OUTPUT +-} +- +-//------------------------------------------------------------------------------ +-// OS Interface Code +-//------------------------------------------------------------------------------ +-use synchronization::interface::Mutex; +- +-/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to +-/// serialize access. +-impl console::interface::Write for QEMUOutput { +- fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { +- // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase +- // readability. +- self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) +- } +-} +- +-impl console::interface::Statistics for QEMUOutput { +- fn chars_written(&self) -> usize { +- self.inner.lock(|inner| inner.chars_written) +- } ++ &super::driver::PL011_UART + } +- +-impl console::interface::All for QEMUOutput {} + +diff -uNr 04_safe_globals/src/bsp/raspberrypi/driver.rs 05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs +--- 04_safe_globals/src/bsp/raspberrypi/driver.rs ++++ 05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs +@@ -0,0 +1,71 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! BSP driver support. ++ ++use super::memory::map::mmio; ++use crate::{bsp::device_driver, console, driver as generic_driver}; ++use core::sync::atomic::{AtomicBool, Ordering}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static PL011_UART: device_driver::PL011Uart = ++ unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; ++static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// This must be called only after successful init of the UART driver. ++fn post_init_uart() -> Result<(), &'static str> { ++ console::register_console(&PL011_UART); ++ ++ Ok(()) ++} ++ ++/// This must be called only after successful init of the GPIO driver. ++fn post_init_gpio() -> Result<(), &'static str> { ++ GPIO.map_pl011_uart(); ++ Ok(()) ++} ++ ++fn driver_uart() -> Result<(), &'static str> { ++ let uart_descriptor = ++ generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); ++ generic_driver::driver_manager().register_driver(uart_descriptor); ++ ++ Ok(()) ++} ++ ++fn driver_gpio() -> Result<(), &'static str> { ++ let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); ++ generic_driver::driver_manager().register_driver(gpio_descriptor); ++ ++ Ok(()) ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Initialize the driver subsystem. ++/// ++/// # Safety ++/// ++/// See child function calls. ++pub unsafe fn init() -> Result<(), &'static str> { ++ static INIT_DONE: AtomicBool = AtomicBool::new(false); ++ if INIT_DONE.load(Ordering::Relaxed) { ++ return Err("Init already done"); ++ } ++ ++ driver_uart()?; ++ driver_gpio()?; ++ ++ INIT_DONE.store(true, Ordering::Relaxed); ++ Ok(()) ++} + +diff -uNr 04_safe_globals/src/bsp/raspberrypi/memory.rs 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs +--- 04_safe_globals/src/bsp/raspberrypi/memory.rs ++++ 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs +@@ -0,0 +1,37 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! BSP Memory Management. ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// The board's physical memory map. ++#[rustfmt::skip] ++pub(super) mod map { ++ ++ pub const GPIO_OFFSET: usize = 0x0020_0000; ++ pub const UART_OFFSET: usize = 0x0020_1000; ++ ++ /// Physical devices. ++ #[cfg(feature = "bsp_rpi3")] ++ pub mod mmio { ++ use super::*; ++ ++ pub const START: usize = 0x3F00_0000; ++ pub const GPIO_START: usize = START + GPIO_OFFSET; ++ pub const PL011_UART_START: usize = START + UART_OFFSET; ++ } ++ ++ /// Physical devices. ++ #[cfg(feature = "bsp_rpi4")] ++ pub mod mmio { ++ use super::*; ++ ++ pub const START: usize = 0xFE00_0000; ++ pub const GPIO_START: usize = START + GPIO_OFFSET; ++ pub const PL011_UART_START: usize = START + UART_OFFSET; ++ } ++} + +diff -uNr 04_safe_globals/src/bsp/raspberrypi.rs 05_drivers_gpio_uart/src/bsp/raspberrypi.rs +--- 04_safe_globals/src/bsp/raspberrypi.rs ++++ 05_drivers_gpio_uart/src/bsp/raspberrypi.rs +@@ -4,5 +4,23 @@ + + //! Top-level BSP file for the Raspberry Pi 3 and 4. + +-pub mod console; + pub mod cpu; ++pub mod driver; ++pub mod memory; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Board identification. ++pub fn board_name() -> &'static str { ++ #[cfg(feature = "bsp_rpi3")] ++ { ++ "Raspberry Pi 3" ++ } ++ ++ #[cfg(feature = "bsp_rpi4")] ++ { ++ "Raspberry Pi 4" ++ } ++} + +diff -uNr 04_safe_globals/src/bsp.rs 05_drivers_gpio_uart/src/bsp.rs +--- 04_safe_globals/src/bsp.rs ++++ 05_drivers_gpio_uart/src/bsp.rs +@@ -4,6 +4,8 @@ + + //! Conditional reexporting of Board Support Packages. + ++mod device_driver; ++ + #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] + mod raspberrypi; + + +diff -uNr 04_safe_globals/src/console/null_console.rs 05_drivers_gpio_uart/src/console/null_console.rs +--- 04_safe_globals/src/console/null_console.rs ++++ 05_drivers_gpio_uart/src/console/null_console.rs +@@ -0,0 +1,41 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Null console. ++ ++use super::interface; ++use core::fmt; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++pub struct NullConsole; ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++pub static NULL_CONSOLE: NullConsole = NullConsole {}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl interface::Write for NullConsole { ++ fn write_char(&self, _c: char) {} ++ ++ fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { ++ fmt::Result::Ok(()) ++ } ++ ++ fn flush(&self) {} ++} ++ ++impl interface::Read for NullConsole { ++ fn clear_rx(&self) {} ++} ++ ++impl interface::Statistics for NullConsole {} ++impl interface::All for NullConsole {} + +diff -uNr 04_safe_globals/src/console.rs 05_drivers_gpio_uart/src/console.rs +--- 04_safe_globals/src/console.rs ++++ 05_drivers_gpio_uart/src/console.rs +@@ -4,7 +4,9 @@ + + //! System console. + +-use crate::bsp; ++mod null_console; ++ ++use crate::synchronization::{self, NullLock}; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions +@@ -16,8 +18,25 @@ + + /// Console write functions. + pub trait Write { ++ /// Write a single character. ++ fn write_char(&self, c: char); ++ + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; ++ ++ /// Block until the last buffered character has been physically put on the TX wire. ++ fn flush(&self); ++ } ++ ++ /// Console read functions. ++ pub trait Read { ++ /// Read a single character. ++ fn read_char(&self) -> char { ++ ' ' ++ } ++ ++ /// Clear RX buffers, if any. ++ fn clear_rx(&self); + } + + /// Console statistics. +@@ -26,19 +45,37 @@ + fn chars_written(&self) -> usize { + 0 + } ++ ++ /// Return the number of characters read. ++ fn chars_read(&self) -> usize { ++ 0 ++ } + } + + /// Trait alias for a full-fledged console. +- pub trait All: Write + Statistics {} ++ pub trait All: Write + Read + Statistics {} + } + + //-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = ++ NullLock::new(&null_console::NULL_CONSOLE); ++ ++//-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- ++use synchronization::interface::Mutex; ++ ++/// Register a new console. ++pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { ++ CUR_CONSOLE.lock(|con| *con = new_console); ++} + +-/// Return a reference to the console. ++/// Return a reference to the currently registered console. + /// + /// This is the global console used by all printing macros. + pub fn console() -> &'static dyn interface::All { +- bsp::console::console() ++ CUR_CONSOLE.lock(|con| *con) + } + +diff -uNr 04_safe_globals/src/cpu.rs 05_drivers_gpio_uart/src/cpu.rs +--- 04_safe_globals/src/cpu.rs ++++ 05_drivers_gpio_uart/src/cpu.rs +@@ -13,4 +13,7 @@ + //-------------------------------------------------------------------------------------------------- + // Architectural Public Reexports + //-------------------------------------------------------------------------------------------------- +-pub use arch_cpu::wait_forever; ++pub use arch_cpu::{nop, wait_forever}; ++ ++#[cfg(feature = "bsp_rpi3")] ++pub use arch_cpu::spin_for_cycles; + +diff -uNr 04_safe_globals/src/driver.rs 05_drivers_gpio_uart/src/driver.rs +--- 04_safe_globals/src/driver.rs ++++ 05_drivers_gpio_uart/src/driver.rs +@@ -0,0 +1,167 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Driver support. ++ ++use crate::{ ++ println, ++ synchronization::{interface::Mutex, NullLock}, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++const NUM_DRIVERS: usize = 5; ++ ++struct DriverManagerInner { ++ next_index: usize, ++ descriptors: [Option; NUM_DRIVERS], ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Driver interfaces. ++pub mod interface { ++ /// Device Driver functions. ++ pub trait DeviceDriver { ++ /// Return a compatibility string for identifying the driver. ++ fn compatible(&self) -> &'static str; ++ ++ /// Called by the kernel to bring up the device. ++ /// ++ /// # Safety ++ /// ++ /// - During init, drivers might do stuff with system-wide impact. ++ unsafe fn init(&self) -> Result<(), &'static str> { ++ Ok(()) ++ } ++ } ++} ++ ++/// Tpye to be used as an optional callback after a driver's init() has run. ++pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; ++ ++/// A descriptor for device drivers. ++#[derive(Copy, Clone)] ++pub struct DeviceDriverDescriptor { ++ device_driver: &'static (dyn interface::DeviceDriver + Sync), ++ post_init_callback: Option, ++} ++ ++/// Provides device driver management functions. ++pub struct DriverManager { ++ inner: NullLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static DRIVER_MANAGER: DriverManager = DriverManager::new(); ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl DriverManagerInner { ++ /// Create an instance. ++ pub const fn new() -> Self { ++ Self { ++ next_index: 0, ++ descriptors: [None; NUM_DRIVERS], ++ } ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl DeviceDriverDescriptor { ++ /// Create an instance. ++ pub fn new( ++ device_driver: &'static (dyn interface::DeviceDriver + Sync), ++ post_init_callback: Option, ++ ) -> Self { ++ Self { ++ device_driver, ++ post_init_callback, ++ } ++ } ++} ++ ++/// Return a reference to the global DriverManager. ++pub fn driver_manager() -> &'static DriverManager { ++ &DRIVER_MANAGER ++} ++ ++impl DriverManager { ++ /// Create an instance. ++ pub const fn new() -> Self { ++ Self { ++ inner: NullLock::new(DriverManagerInner::new()), ++ } ++ } ++ ++ /// Register a device driver with the kernel. ++ pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { ++ self.inner.lock(|inner| { ++ inner.descriptors[inner.next_index] = Some(descriptor); ++ inner.next_index += 1; ++ }) ++ } ++ ++ /// Helper for iterating over registered drivers. ++ fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { ++ self.inner.lock(|inner| { ++ inner ++ .descriptors ++ .iter() ++ .filter_map(|x| x.as_ref()) ++ .for_each(f) ++ }) ++ } ++ ++ /// Fully initialize all drivers. ++ /// ++ /// # Safety ++ /// ++ /// - During init, drivers might do stuff with system-wide impact. ++ pub unsafe fn init_drivers(&self) { ++ self.for_each_descriptor(|descriptor| { ++ // 1. Initialize driver. ++ if let Err(x) = descriptor.device_driver.init() { ++ panic!( ++ "Error initializing driver: {}: {}", ++ descriptor.device_driver.compatible(), ++ x ++ ); ++ } ++ ++ // 2. Call corresponding post init callback. ++ if let Some(callback) = &descriptor.post_init_callback { ++ if let Err(x) = callback() { ++ panic!( ++ "Error during driver post-init callback: {}: {}", ++ descriptor.device_driver.compatible(), ++ x ++ ); ++ } ++ } ++ }); ++ } ++ ++ /// Enumerate all registered device drivers. ++ pub fn enumerate(&self) { ++ let mut i: usize = 1; ++ self.for_each_descriptor(|descriptor| { ++ println!(" {}. {}", i, descriptor.device_driver.compatible()); ++ ++ i += 1; ++ }); ++ } ++} + +diff -uNr 04_safe_globals/src/main.rs 05_drivers_gpio_uart/src/main.rs +--- 04_safe_globals/src/main.rs ++++ 05_drivers_gpio_uart/src/main.rs +@@ -106,6 +106,7 @@ + //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. + //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + ++#![allow(clippy::upper_case_acronyms)] + #![feature(asm_const)] + #![feature(format_args_nl)] + #![feature(panic_info_message)] +@@ -116,6 +117,7 @@ + mod bsp; + mod console; + mod cpu; ++mod driver; + mod panic_wait; + mod print; + mod synchronization; +@@ -125,13 +127,42 @@ + /// # Safety + /// + /// - Only a single core must be active and running this function. ++/// - The init calls in this function must appear in the correct order. + unsafe fn kernel_init() -> ! { +- use console::console; ++ // Initialize the BSP driver subsystem. ++ if let Err(x) = bsp::driver::init() { ++ panic!("Error initializing BSP driver subsystem: {}", x); ++ } ++ ++ // Initialize all device drivers. ++ driver::driver_manager().init_drivers(); ++ // println! is usable from here on. + +- println!("[0] Hello from Rust!"); ++ // Transition from unsafe to safe. ++ kernel_main() ++} + +- println!("[1] Chars written: {}", console().chars_written()); ++/// The main function running after the early init. ++fn kernel_main() -> ! { ++ use console::console; + +- println!("[2] Stopping here."); +- cpu::wait_forever() ++ println!( ++ "[0] {} version {}", ++ env!("CARGO_PKG_NAME"), ++ env!("CARGO_PKG_VERSION") ++ ); ++ println!("[1] Booting on: {}", bsp::board_name()); ++ ++ println!("[2] Drivers loaded:"); ++ driver::driver_manager().enumerate(); ++ ++ println!("[3] Chars written: {}", console().chars_written()); ++ println!("[4] Echoing input now"); ++ ++ // Discard any spurious received characters before going into echo mode. ++ console().clear_rx(); ++ loop { ++ let c = console().read_char(); ++ console().write_char(c); ++ } + } + +diff -uNr 04_safe_globals/tests/boot_test_string.rb 05_drivers_gpio_uart/tests/boot_test_string.rb +--- 04_safe_globals/tests/boot_test_string.rb ++++ 05_drivers_gpio_uart/tests/boot_test_string.rb +@@ -1,3 +1,3 @@ + # frozen_string_literal: true + +-EXPECTED_PRINT = 'Stopping here' ++EXPECTED_PRINT = 'Echoing input now' + +``` diff --git a/05_drivers_gpio_uart/build.rs b/05_drivers_gpio_uart/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/05_drivers_gpio_uart/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs b/05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..f1f1e9aff --- /dev/null +++ b/05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Spin for `n` cycles. +#[cfg(feature = "bsp_rpi3")] +#[inline(always)] +pub fn spin_for_cycles(n: usize) { + for _ in 0..n { + asm::nop(); + } +} + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff --git a/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.rs b/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..2a6c46492 --- /dev/null +++ b/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff --git a/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s b/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..0011c6074 --- /dev/null +++ b/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed on the boot core. Park it otherwise. + mrs x0, MPIDR_EL1 + and x0, x0, {CONST_CORE_ID_MASK} + ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x0, x1 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Jump to Rust code. + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/05_drivers_gpio_uart/src/bsp.rs b/05_drivers_gpio_uart/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/05_drivers_gpio_uart/src/bsp/device_driver.rs b/05_drivers_gpio_uart/src/bsp/device_driver.rs new file mode 100644 index 000000000..64049a4cf --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs b/05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..1c343d1d7 --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..920b4c00c --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::cpu; + + // Make an educated guess for a good delay value (Sequence described in the BCM2837 + // peripherals PDF). + // + // - According to Wikipedia, the fastest RPi4 clocks around 1.5 GHz. + // - The Linux 2837 GPIO driver waits 1 µs between the steps. + // + // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs + // would the CPU be clocked at 2 GHz. + const DELAY: usize = 2000; + + self.registers.GPPUD.write(GPPUD::PUD::Off); + cpu::spin_for_cycles(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + cpu::spin_for_cycles(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..d92612ea8 --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff --git a/05_drivers_gpio_uart/src/bsp/device_driver/common.rs b/05_drivers_gpio_uart/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..dfe7d8ef3 --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..3ea864dc7 --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs new file mode 100644 index 000000000..0d585229e --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP console facilities. + +use crate::console; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the console. +pub fn console() -> &'static dyn console::interface::All { + &super::driver::PL011_UART +} diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..2a80ee2c5 --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld b/05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..f6c188434 --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..cdca14b8a --- /dev/null +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } +} diff --git a/05_drivers_gpio_uart/src/console.rs b/05_drivers_gpio_uart/src/console.rs new file mode 100644 index 000000000..a83f86fe0 --- /dev/null +++ b/05_drivers_gpio_uart/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization::{self, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) +} diff --git a/05_drivers_gpio_uart/src/console/null_console.rs b/05_drivers_gpio_uart/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/05_drivers_gpio_uart/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/05_drivers_gpio_uart/src/cpu.rs b/05_drivers_gpio_uart/src/cpu.rs new file mode 100644 index 000000000..eacb8924a --- /dev/null +++ b/05_drivers_gpio_uart/src/cpu.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "bsp_rpi3")] +pub use arch_cpu::spin_for_cycles; diff --git a/05_drivers_gpio_uart/src/cpu/boot.rs b/05_drivers_gpio_uart/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/05_drivers_gpio_uart/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/05_drivers_gpio_uart/src/driver.rs b/05_drivers_gpio_uart/src/driver.rs new file mode 100644 index 000000000..feef34e20 --- /dev/null +++ b/05_drivers_gpio_uart/src/driver.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + println, + synchronization::{interface::Mutex, NullLock}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + println!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/05_drivers_gpio_uart/src/main.rs b/05_drivers_gpio_uart/src/main.rs new file mode 100644 index 000000000..11d342ce4 --- /dev/null +++ b/05_drivers_gpio_uart/src/main.rs @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![feature(asm_const)] +#![feature(format_args_nl)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![no_main] +#![no_std] + +mod bsp; +mod console; +mod cpu; +mod driver; +mod panic_wait; +mod print; +mod synchronization; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order. +unsafe fn kernel_init() -> ! { + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + use console::console; + + println!( + "[0] {} version {}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + println!("[1] Booting on: {}", bsp::board_name()); + + println!("[2] Drivers loaded:"); + driver::driver_manager().enumerate(); + + println!("[3] Chars written: {}", console().chars_written()); + println!("[4] Echoing input now"); + + // Discard any spurious received characters before going into echo mode. + console().clear_rx(); + loop { + let c = console().read_char(); + console().write_char(c); + } +} diff --git a/05_drivers_gpio_uart/src/panic_wait.rs b/05_drivers_gpio_uart/src/panic_wait.rs new file mode 100644 index 000000000..5bb0896e4 --- /dev/null +++ b/05_drivers_gpio_uart/src/panic_wait.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + cpu::wait_forever() +} diff --git a/05_drivers_gpio_uart/src/print.rs b/05_drivers_gpio_uart/src/print.rs new file mode 100644 index 000000000..6de99572d --- /dev/null +++ b/05_drivers_gpio_uart/src/print.rs @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} diff --git a/05_drivers_gpio_uart/src/synchronization.rs b/05_drivers_gpio_uart/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/05_drivers_gpio_uart/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/05_drivers_gpio_uart/tests/boot_test_string.rb b/05_drivers_gpio_uart/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/05_drivers_gpio_uart/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/05_safe_globals/.vscode/settings.json b/05_safe_globals/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/05_safe_globals/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/05_safe_globals/Cargo.lock b/05_safe_globals/Cargo.lock deleted file mode 100644 index fd6d5c737..000000000 --- a/05_safe_globals/Cargo.lock +++ /dev/null @@ -1,32 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/05_safe_globals/Cargo.toml b/05_safe_globals/Cargo.toml deleted file mode 100644 index 517455433..000000000 --- a/05_safe_globals/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = [] -bsp_rpi4 = [] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/05_safe_globals/Makefile b/05_safe_globals/Makefile deleted file mode 100644 index a9b0f82ce..000000000 --- a/05_safe_globals/Makefile +++ /dev/null @@ -1,98 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu clippy clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -endif - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/05_safe_globals/README.md b/05_safe_globals/README.md deleted file mode 100644 index 1cbe90b8e..000000000 --- a/05_safe_globals/README.md +++ /dev/null @@ -1,331 +0,0 @@ -# Tutorial 05 - Safe Globals - -## tl;dr - -- A pseudo-lock is introduced. -- It is a first showcase of OS synchronization primitives and enables safe access to a global data - structure. - -## Mutable globals in Rust - -When we introduced the globally usable `print!` macros in [tutorial 03], we cheated a bit. Calling -`core::fmt`'s `write_fmt()` function, which takes an `&mut self`, was only working because on each -call, a new instance of `QEMUOutput` was created. - -If we would want to preserve some state, e.g. statistics about the number of characters written, we -need to make a single global instance of `QEMUOutput` (in Rust, using the `static` keyword). - -A `static QEMU_OUTPUT`, however, would not allow to call functions taking `&mut self`. For that, we -would need a `static mut`, but calling functions that mutate state on `static mut`s is unsafe. The -Rust compiler's reasoning for this is that it can then not prevent anymore that multiple -cores/threads are mutating the data concurrently (it is a global, so everyone can reference it from -anywhere. The borrow checker can't help here). - -The solution to this problem is to wrap the global into a synchronization primitive. In our case, a -variant of a *MUTual EXclusion* primitive. `Mutex` is introduced as a trait in `synchronization.rs`, -and implemented by the `NullLock` in the same file. In order to make the code lean for teaching -purposes, it leaves out the actual architecture-specific logic for protection against concurrent -access, since we don't need it as long as the kernel only executes on a single core with interrupts -disabled. That is also why it is implemented in the same file as the interface itself. In later -tutorials, an implementation might move to the `_arch` once it pulls in arch-specific code that can -not be further abstracted. - -The `NullLock` focuses on showcasing the Rust core concept of [interior mutability]. Make sure to -read up on it. I also recommend to read this article about an [accurate mental model for Rust's -reference types]. - -If you want to compare the `NullLock` to some real-world mutex implementations, you can check out -implemntations in the [spin crate] or the [parking lot crate]. - -[tutorial 03]: ../03_hacky_hello_world -[interior mutability]: https://doc.rust-lang.org/std/cell/index.html -[accurate mental model for Rust's reference types]: https://docs.rs/dtolnay/0.0.6/dtolnay/macro._02__reference_types.html -[spin crate]: https://github.com/mvdnes/spin-rs -[parking lot crate]: https://github.com/Amanieu/parking_lot - -## Test it - -```console -$ make qemu -[...] -[0] Hello from pure Rust! -[1] Chars written: 27 -[2] Stopping here. -``` - -## Diff to previous -```diff - -diff -uNr 04_zero_overhead_abstraction/src/bsp/raspberrypi/console.rs 05_safe_globals/src/bsp/raspberrypi/console.rs ---- 04_zero_overhead_abstraction/src/bsp/raspberrypi/console.rs -+++ 05_safe_globals/src/bsp/raspberrypi/console.rs -@@ -4,7 +4,7 @@ - - //! BSP console facilities. - --use crate::console; -+use crate::{console, synchronization, synchronization::NullLock}; - use core::fmt; - - //-------------------------------------------------------------------------------------------------- -@@ -12,25 +12,64 @@ - //-------------------------------------------------------------------------------------------------- - - /// A mystical, magical device for generating QEMU output out of the void. --struct QEMUOutput; -+/// -+/// The mutex protected part. -+struct QEMUOutputInner { -+ chars_written: usize, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// The main struct. -+pub struct QEMUOutput { -+ inner: NullLock, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Global instances -+//-------------------------------------------------------------------------------------------------- -+ -+static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); - - //-------------------------------------------------------------------------------------------------- - // Private Code - //-------------------------------------------------------------------------------------------------- - -+impl QEMUOutputInner { -+ const fn new() -> QEMUOutputInner { -+ QEMUOutputInner { chars_written: 0 } -+ } -+ -+ /// Send a character. -+ fn write_char(&mut self, c: char) { -+ unsafe { -+ core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); -+ } -+ -+ self.chars_written += 1; -+ } -+} -+ - /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are - /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, - /// we get `write_fmt()` automatically. - /// -+/// The function takes an `&mut self`, so it must be implemented for the inner struct. -+/// - /// See [`src/print.rs`]. - /// - /// [`src/print.rs`]: ../../print/index.html --impl fmt::Write for QEMUOutput { -+impl fmt::Write for QEMUOutputInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { -- unsafe { -- core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); -+ // Convert newline to carrige return + newline. -+ if c == '\n' { -+ self.write_char('\r') - } -+ -+ self.write_char(c); - } - - Ok(()) -@@ -41,7 +80,37 @@ - // Public Code - //-------------------------------------------------------------------------------------------------- - -+impl QEMUOutput { -+ /// Create a new instance. -+ pub const fn new() -> QEMUOutput { -+ QEMUOutput { -+ inner: NullLock::new(QEMUOutputInner::new()), -+ } -+ } -+} -+ - /// Return a reference to the console. --pub fn console() -> impl console::interface::Write { -- QEMUOutput {} -+pub fn console() -> &'static impl console::interface::All { -+ &QEMU_OUTPUT -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+use synchronization::interface::Mutex; -+ -+/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to -+/// serialize access. -+impl console::interface::Write for QEMUOutput { -+ fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { -+ // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase -+ // readability. -+ self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) -+ } -+} -+ -+impl console::interface::Statistics for QEMUOutput { -+ fn chars_written(&self) -> usize { -+ self.inner.lock(|inner| inner.chars_written) -+ } - } - -diff -uNr 04_zero_overhead_abstraction/src/console.rs 05_safe_globals/src/console.rs ---- 04_zero_overhead_abstraction/src/console.rs -+++ 05_safe_globals/src/console.rs -@@ -10,10 +10,22 @@ - - /// Console interfaces. - pub mod interface { -+ use core::fmt; -+ - /// Console write functions. -- /// -- /// `core::fmt::Write` is exactly what we need for now. Re-export it here because -- /// implementing `console::Write` gives a better hint to the reader about the -- /// intention. -- pub use core::fmt::Write; -+ pub trait Write { -+ /// Write a Rust format string. -+ fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; -+ } -+ -+ /// Console statistics. -+ pub trait Statistics { -+ /// Return the number of characters written. -+ fn chars_written(&self) -> usize { -+ 0 -+ } -+ } -+ -+ /// Trait alias for a full-fledged console. -+ pub trait All = Write + Statistics; - } - -diff -uNr 04_zero_overhead_abstraction/src/main.rs 05_safe_globals/src/main.rs ---- 04_zero_overhead_abstraction/src/main.rs -+++ 05_safe_globals/src/main.rs -@@ -95,6 +95,7 @@ - #![feature(format_args_nl)] - #![feature(naked_functions)] - #![feature(panic_info_message)] -+#![feature(trait_alias)] - #![no_main] - #![no_std] - -@@ -108,6 +109,7 @@ - mod panic_wait; - mod print; - mod runtime_init; -+mod synchronization; - - /// Early init code. - /// -@@ -115,8 +117,15 @@ - /// - /// - Only a single core must be active and running this function. - unsafe fn kernel_init() -> ! { -+ use console::interface::Statistics; -+ - println!("[0] Hello from pure Rust!"); - -- println!("[1] Stopping here."); -+ println!( -+ "[1] Chars written: {}", -+ bsp::console::console().chars_written() -+ ); -+ -+ println!("[2] Stopping here."); - cpu::wait_forever() - } - -diff -uNr 04_zero_overhead_abstraction/src/synchronization.rs 05_safe_globals/src/synchronization.rs ---- 04_zero_overhead_abstraction/src/synchronization.rs -+++ 05_safe_globals/src/synchronization.rs -@@ -0,0 +1,76 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Synchronization primitives. -+//! -+//! Suggested literature: -+//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -+//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -+//! - https://doc.rust-lang.org/std/cell/index.html -+ -+use core::cell::UnsafeCell; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Synchronization interfaces. -+pub mod interface { -+ -+ /// Any object implementing this trait guarantees exclusive access to the data wrapped within -+ /// the Mutex for the duration of the provided closure. -+ pub trait Mutex { -+ /// The type of the data that is wrapped by this mutex. -+ type Data; -+ -+ /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. -+ fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; -+ } -+} -+ -+/// A pseudo-lock for teaching purposes. -+/// -+/// In contrast to a real Mutex implementation, does not protect against concurrent access from -+/// other cores to the contained data. This part is preserved for later lessons. -+/// -+/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -+/// executing single-threaded, aka only running on a single core with interrupts disabled. -+pub struct NullLock -+where -+ T: ?Sized, -+{ -+ data: UnsafeCell, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+unsafe impl Send for NullLock where T: ?Sized + Send {} -+unsafe impl Sync for NullLock where T: ?Sized + Send {} -+ -+impl NullLock { -+ /// Create an instance. -+ pub const fn new(data: T) -> Self { -+ Self { -+ data: UnsafeCell::new(data), -+ } -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+ -+impl interface::Mutex for NullLock { -+ type Data = T; -+ -+ fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { -+ // In a real lock, there would be code encapsulating this line that ensures that this -+ // mutable reference will ever only be given out once at a time. -+ let data = unsafe { &mut *self.data.get() }; -+ -+ f(data) -+ } -+} - -``` diff --git a/05_safe_globals/build.rs b/05_safe_globals/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/05_safe_globals/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/05_safe_globals/src/_arch/aarch64/cpu.rs b/05_safe_globals/src/_arch/aarch64/cpu.rs deleted file mode 100644 index d49c8aba0..000000000 --- a/05_safe_globals/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - use crate::runtime_init; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); - runtime_init::runtime_init() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} diff --git a/05_safe_globals/src/_arch/aarch64/cpu/smp.rs b/05_safe_globals/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/05_safe_globals/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/05_safe_globals/src/bsp.rs b/05_safe_globals/src/bsp.rs deleted file mode 100644 index db48385eb..000000000 --- a/05_safe_globals/src/bsp.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/05_safe_globals/src/bsp/raspberrypi.rs b/05_safe_globals/src/bsp/raspberrypi.rs deleted file mode 100644 index 0ad1b2aed..000000000 --- a/05_safe_globals/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod memory; diff --git a/05_safe_globals/src/bsp/raspberrypi/console.rs b/05_safe_globals/src/bsp/raspberrypi/console.rs deleted file mode 100644 index 074f4fa17..000000000 --- a/05_safe_globals/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,116 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use crate::{console, synchronization, synchronization::NullLock}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// A mystical, magical device for generating QEMU output out of the void. -/// -/// The mutex protected part. -struct QEMUOutputInner { - chars_written: usize, -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The main struct. -pub struct QEMUOutput { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl QEMUOutputInner { - const fn new() -> QEMUOutputInner { - QEMUOutputInner { chars_written: 0 } - } - - /// Send a character. - fn write_char(&mut self, c: char) { - unsafe { - core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); - } - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for QEMUOutputInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - // Convert newline to carrige return + newline. - if c == '\n' { - self.write_char('\r') - } - - self.write_char(c); - } - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl QEMUOutput { - /// Create a new instance. - pub const fn new() -> QEMUOutput { - QEMUOutput { - inner: NullLock::new(QEMUOutputInner::new()), - } - } -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &QEMU_OUTPUT -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to -/// serialize access. -impl console::interface::Write for QEMUOutput { - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } -} - -impl console::interface::Statistics for QEMUOutput { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } -} diff --git a/05_safe_globals/src/bsp/raspberrypi/cpu.rs b/05_safe_globals/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/05_safe_globals/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/05_safe_globals/src/bsp/raspberrypi/link.ld b/05_safe_globals/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/05_safe_globals/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/05_safe_globals/src/bsp/raspberrypi/memory.rs b/05_safe_globals/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 51cc958ad..000000000 --- a/05_safe_globals/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/05_safe_globals/src/console.rs b/05_safe_globals/src/console.rs deleted file mode 100644 index 12b31c636..000000000 --- a/05_safe_globals/src/console.rs +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Statistics; -} diff --git a/05_safe_globals/src/cpu.rs b/05_safe_globals/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/05_safe_globals/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/05_safe_globals/src/cpu/smp.rs b/05_safe_globals/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/05_safe_globals/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/05_safe_globals/src/main.rs b/05_safe_globals/src/main.rs deleted file mode 100644 index 6a57de237..000000000 --- a/05_safe_globals/src/main.rs +++ /dev/null @@ -1,131 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![feature(format_args_nl)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod memory; -mod panic_wait; -mod print; -mod runtime_init; -mod synchronization; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -unsafe fn kernel_init() -> ! { - use console::interface::Statistics; - - println!("[0] Hello from pure Rust!"); - - println!( - "[1] Chars written: {}", - bsp::console::console().chars_written() - ); - - println!("[2] Stopping here."); - cpu::wait_forever() -} diff --git a/05_safe_globals/src/memory.rs b/05_safe_globals/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/05_safe_globals/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/05_safe_globals/src/panic_wait.rs b/05_safe_globals/src/panic_wait.rs deleted file mode 100644 index b4d5bc1ae..000000000 --- a/05_safe_globals/src/panic_wait.rs +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{cpu, println}; -use core::panic::PanicInfo; - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - println!("\nKernel panic: {}", args); - } else { - println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/05_safe_globals/src/print.rs b/05_safe_globals/src/print.rs deleted file mode 100644 index 77ebd8b40..000000000 --- a/05_safe_globals/src/print.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} diff --git a/05_safe_globals/src/runtime_init.rs b/05_safe_globals/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/05_safe_globals/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/05_safe_globals/src/synchronization.rs b/05_safe_globals/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/05_safe_globals/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/06_drivers_gpio_uart/.vscode/settings.json b/06_drivers_gpio_uart/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/06_drivers_gpio_uart/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/06_drivers_gpio_uart/Cargo.lock b/06_drivers_gpio_uart/Cargo.lock deleted file mode 100644 index 7b2456e16..000000000 --- a/06_drivers_gpio_uart/Cargo.lock +++ /dev/null @@ -1,33 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "register", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/06_drivers_gpio_uart/Cargo.toml b/06_drivers_gpio_uart/Cargo.toml deleted file mode 100644 index b8906da1f..000000000 --- a/06_drivers_gpio_uart/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Optional dependencies -register = { version = "1.x.x", optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/06_drivers_gpio_uart/Makefile b/06_drivers_gpio_uart/Makefile deleted file mode 100644 index 06c268de7..000000000 --- a/06_drivers_gpio_uart/Makefile +++ /dev/null @@ -1,117 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DEV = --privileged -v /dev:/dev - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINITERM = ruby ../utils/miniterm.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu miniterm clippy clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -endif - -miniterm: - @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/06_drivers_gpio_uart/README.md b/06_drivers_gpio_uart/README.md deleted file mode 100644 index 1bd8b26ae..000000000 --- a/06_drivers_gpio_uart/README.md +++ /dev/null @@ -1,1319 +0,0 @@ -# Tutorial 06 - Drivers: GPIO and UART - -## tl;dr - -- Now that we enabled safe globals in the previous tutorial, the infrastructure is laid for adding - the first real device drivers. -- We throw out the magic QEMU console and use a real `UART` now. Like serious embedded hackers do! - -## Notable additions - -- For the first time, we will be able to run the code on the real hardware. - - Therefore, building is now differentiated between the **RPi 3** and the **RPi4**. - - By default, all `Makefile` targets will build for the **RPi 3**. - - In order to build for the the **RPi4**, prepend `BSP=rpi4` to each target. For example: - - `BSP=rpi4 make` - - `BSP=rpi4 make doc` - - Unfortunately, QEMU does not yet support the **RPi4**, so `BSP=rpi4 make qemu` won't work. -- A `driver::interface::DeviceDriver` trait is added for abstracting `BSP` driver implementations - from kernel code. -- Drivers are stored in `src/bsp/device_driver`, and can be reused between `BSP`s. - - We introduce the `GPIO` driver, which pinmuxes the RPi's PL011 UART. - - Most importantly, the `PL011Uart` driver: It implements the `console::interface::*` traits and - is from now on used as the main system console output. -- `BSP`s now contain a memory map in `src/bsp/raspberrypi/memory.rs`. In the specific case, they contain the - Raspberry's `MMIO` addresses which are used to instantiate the respectivedevice drivers. -- We also modify the `panic!` handler, so that it does not anymore rely on `println!`, which uses - the globally-shared instance of the `UART` that might be locked when an error is encountered (for - now this can't happen due to the `NullLock`, but with a real lock it becomes an issue). - - Instead, it creates a new UART driver instance, re-initializes the device and uses that one to - print. This increases the chances that the system is able to print a final important message - before it suspends itself. - -## Boot it from SD card - -Some steps for preparing the SD card differ between RPi3 and RPi4, so be careful. - -### Common for both - -1. Make a single `FAT32` partition named `boot`. -2. On the card, generate a file named `config.txt` with the following contents: - -```txt -arm_64bit=1 -init_uart_clock=48000000 -``` -### Pi 3 - -3. Copy the following files from the [Raspberry Pi firmware repo](https://github.com/raspberrypi/firmware/tree/master/boot) onto the SD card: - - [bootcode.bin](https://github.com/raspberrypi/firmware/raw/master/boot/bootcode.bin) - - [fixup.dat](https://github.com/raspberrypi/firmware/raw/master/boot/fixup.dat) - - [start.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start.elf) -4. Run `make` and copy the [kernel8.img](kernel8.img) onto the SD card. - -### Pi 4 - -3. Copy the following files from the [Raspberry Pi firmware repo](https://github.com/raspberrypi/firmware/tree/master/boot) onto the SD card: - - [fixup4.dat](https://github.com/raspberrypi/firmware/raw/master/boot/fixup4.dat) - - [start4.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start4.elf) - - [bcm2711-rpi-4-b.dtb](https://github.com/raspberrypi/firmware/raw/master/boot/bcm2711-rpi-4-b.dtb) -4. Run `BSP=rpi4 make` and copy the [kernel8.img](kernel8.img) onto the SD card. - -_**Note**: Should it not work on your RPi4, try renaming `start4.elf` to `start.elf` (without the 4) -on the SD card._ - -### Common again - -5. Insert the SD card into the RPi and connect the USB serial to your host PC. - - Wiring diagram at [top-level README](../README.md#usb-serial). -6. Run the `miniterm` target, which opens the UART device on the host: - -```console -$ make miniterm -``` - -> ❗ **NOTE**: `Miniterm` assumes a default serial device name of `/dev/ttyUSB0`. Depending on your -> host operating system, the device name might differ. For example, on `macOS`, it might be -> something like `/dev/tty.usbserial-0001`. In this case, please give the name explicitly: - - -```console -$ DEV_SERIAL=/dev/tty.usbserial-0001 make miniterm -``` - -7. Hit Enter after seeing "`Connected`" to kick off the kernel boot process and observe - the output: - -```console -Miniterm 1.0 - - -[MT] ✅ Connected -[0] Booting on: Raspberry Pi 3 -[1] Drivers loaded: - 1. BCM GPIO - 2. BCM PL011 UART -[2] Chars written: 93 -[3] Echoing input now -``` - -8. Exit by pressing ctrl-c. - -## Diff to previous -```diff - -diff -uNr 05_safe_globals/Cargo.toml 06_drivers_gpio_uart/Cargo.toml ---- 05_safe_globals/Cargo.toml -+++ 06_drivers_gpio_uart/Cargo.toml -@@ -10,8 +10,8 @@ - # The features section is used to select the target board. - [features] - default = [] --bsp_rpi3 = [] --bsp_rpi4 = [] -+bsp_rpi3 = ["register"] -+bsp_rpi4 = ["register"] - - ##-------------------------------------------------------------------------------------------------- - ## Dependencies -@@ -19,6 +19,9 @@ - - [dependencies] - -+# Optional dependencies -+register = { version = "1.x.x", optional = true } -+ - # Platform specific dependencies - [target.'cfg(target_arch = "aarch64")'.dependencies] - cortex-a = { version = "5.x.x" } - -diff -uNr 05_safe_globals/Makefile 06_drivers_gpio_uart/Makefile ---- 05_safe_globals/Makefile -+++ 06_drivers_gpio_uart/Makefile -@@ -5,6 +5,12 @@ - # Default to the RPi3 - BSP ?= rpi3 - -+# Default to a serial device name that is common in Linux. -+DEV_SERIAL ?= /dev/ttyUSB0 -+ -+# Query the host system's kernel name -+UNAME_S = $(shell uname -s) -+ - # BSP-specific arguments - ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat -@@ -51,13 +57,23 @@ - DOCKER_IMAGE = rustembedded/osdev-utils - DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial - DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -+DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -+DOCKER_ARG_DEV = --privileged -v /dev:/dev - - DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) - DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - --EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -+# Dockerize commands that require USB device passthrough only on Linux -+ifeq ($(UNAME_S),Linux) -+ DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) -+ -+ DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) -+endif -+ -+EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -+EXEC_MINITERM = ruby ../utils/miniterm.rb - --.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu clippy clean readelf objdump nm check -+.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu miniterm clippy clean readelf objdump nm check - - all: $(KERNEL_BIN) - -@@ -78,6 +94,9 @@ - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) - endif - -+miniterm: -+ @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) -+ - clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - - -diff -uNr 05_safe_globals/src/_arch/aarch64/cpu.rs 06_drivers_gpio_uart/src/_arch/aarch64/cpu.rs ---- 05_safe_globals/src/_arch/aarch64/cpu.rs -+++ 06_drivers_gpio_uart/src/_arch/aarch64/cpu.rs -@@ -37,6 +37,17 @@ - // Public Code - //-------------------------------------------------------------------------------------------------- - -+pub use asm::nop; -+ -+/// Spin for `n` cycles. -+#[cfg(feature = "bsp_rpi3")] -+#[inline(always)] -+pub fn spin_for_cycles(n: usize) { -+ for _ in 0..n { -+ asm::nop(); -+ } -+} -+ - /// Pause execution on the core. - #[inline(always)] - pub fn wait_forever() -> ! { - -diff -uNr 05_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ---- 05_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -+++ 06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -@@ -0,0 +1,221 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! GPIO Driver. -+ -+use crate::{ -+ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, -+ synchronization::NullLock, -+}; -+use register::{mmio::*, register_bitfields, register_structs}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+// GPIO registers. -+// -+// Descriptions taken from -+// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -+// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -+register_bitfields! { -+ u32, -+ -+ /// GPIO Function Select 1 -+ GPFSEL1 [ -+ /// Pin 15 -+ FSEL15 OFFSET(15) NUMBITS(3) [ -+ Input = 0b000, -+ Output = 0b001, -+ AltFunc0 = 0b100 // PL011 UART RX -+ -+ ], -+ -+ /// Pin 14 -+ FSEL14 OFFSET(12) NUMBITS(3) [ -+ Input = 0b000, -+ Output = 0b001, -+ AltFunc0 = 0b100 // PL011 UART TX -+ ] -+ ], -+ -+ /// GPIO Pull-up/down Register -+ /// -+ /// BCM2837 only. -+ GPPUD [ -+ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. -+ PUD OFFSET(0) NUMBITS(2) [ -+ Off = 0b00, -+ PullDown = 0b01, -+ PullUp = 0b10 -+ ] -+ ], -+ -+ /// GPIO Pull-up/down Clock Register 0 -+ /// -+ /// BCM2837 only. -+ GPPUDCLK0 [ -+ /// Pin 15 -+ PUDCLK15 OFFSET(15) NUMBITS(1) [ -+ NoEffect = 0, -+ AssertClock = 1 -+ ], -+ -+ /// Pin 14 -+ PUDCLK14 OFFSET(14) NUMBITS(1) [ -+ NoEffect = 0, -+ AssertClock = 1 -+ ] -+ ], -+ -+ /// GPIO Pull-up / Pull-down Register 0 -+ /// -+ /// BCM2711 only. -+ GPIO_PUP_PDN_CNTRL_REG0 [ -+ /// Pin 15 -+ GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ -+ NoResistor = 0b00, -+ PullUp = 0b01 -+ ], -+ -+ /// Pin 14 -+ GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ -+ NoResistor = 0b00, -+ PullUp = 0b01 -+ ] -+ ] -+} -+ -+register_structs! { -+ #[allow(non_snake_case)] -+ RegisterBlock { -+ (0x00 => _reserved1), -+ (0x04 => GPFSEL1: ReadWrite), -+ (0x08 => _reserved2), -+ (0x94 => GPPUD: ReadWrite), -+ (0x98 => GPPUDCLK0: ReadWrite), -+ (0x9C => _reserved3), -+ (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), -+ (0xE8 => @END), -+ } -+} -+ -+/// Abstraction for the associated MMIO registers. -+type Registers = MMIODerefWrapper; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+pub struct GPIOInner { -+ registers: Registers, -+} -+ -+// Export the inner struct so that BSPs can use it for the panic handler. -+pub use GPIOInner as PanicGPIO; -+ -+/// Representation of the GPIO HW. -+pub struct GPIO { -+ inner: NullLock, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl GPIOInner { -+ /// Create an instance. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ Self { -+ registers: Registers::new(mmio_start_addr), -+ } -+ } -+ -+ /// Disable pull-up/down on pins 14 and 15. -+ #[cfg(feature = "bsp_rpi3")] -+ fn disable_pud_14_15_bcm2837(&mut self) { -+ use crate::cpu; -+ -+ // Make an educated guess for a good delay value (Sequence described in the BCM2837 -+ // peripherals PDF). -+ // -+ // - According to Wikipedia, the fastest Pi3 clocks around 1.4 GHz. -+ // - The Linux 2837 GPIO driver waits 1 µs between the steps. -+ // -+ // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs -+ // would the CPU be clocked at 2 GHz. -+ const DELAY: usize = 2000; -+ -+ self.registers.GPPUD.write(GPPUD::PUD::Off); -+ cpu::spin_for_cycles(DELAY); -+ -+ self.registers -+ .GPPUDCLK0 -+ .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); -+ cpu::spin_for_cycles(DELAY); -+ -+ self.registers.GPPUD.write(GPPUD::PUD::Off); -+ self.registers.GPPUDCLK0.set(0); -+ } -+ -+ /// Disable pull-up/down on pins 14 and 15. -+ #[cfg(feature = "bsp_rpi4")] -+ fn disable_pud_14_15_bcm2711(&mut self) { -+ self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( -+ GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp -+ + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, -+ ); -+ } -+ -+ /// Map PL011 UART as standard output. -+ /// -+ /// TX to pin 14 -+ /// RX to pin 15 -+ pub fn map_pl011_uart(&mut self) { -+ // Select the UART on pins 14 and 15. -+ self.registers -+ .GPFSEL1 -+ .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); -+ -+ // Disable pull-up/down on pins 14 and 15. -+ #[cfg(feature = "bsp_rpi3")] -+ self.disable_pud_14_15_bcm2837(); -+ -+ #[cfg(feature = "bsp_rpi4")] -+ self.disable_pud_14_15_bcm2711(); -+ } -+} -+ -+impl GPIO { -+ /// Create an instance. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ Self { -+ inner: NullLock::new(GPIOInner::new(mmio_start_addr)), -+ } -+ } -+ -+ /// Concurrency safe version of `GPIOInner.map_pl011_uart()` -+ pub fn map_pl011_uart(&self) { -+ self.inner.lock(|inner| inner.map_pl011_uart()) -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+use synchronization::interface::Mutex; -+ -+impl driver::interface::DeviceDriver for GPIO { -+ fn compatible(&self) -> &'static str { -+ "BCM GPIO" -+ } -+} - -diff -uNr 05_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ---- 05_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -+++ 06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -@@ -0,0 +1,305 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! PL011 UART driver. -+ -+use crate::{ -+ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, -+ synchronization::NullLock, -+}; -+use core::fmt; -+use register::{mmio::*, register_bitfields, register_structs}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+// PL011 UART registers. -+// -+// Descriptions taken from -+// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -+register_bitfields! { -+ u32, -+ -+ /// Flag Register -+ FR [ -+ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the -+ /// Line Control Register, UARTLCR_ LCRH. -+ /// -+ /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If -+ /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does -+ /// not indicate if there is data in the transmit shift register. -+ TXFE OFFSET(7) NUMBITS(1) [], -+ -+ /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the -+ /// UARTLCR_ LCRH Register. -+ /// -+ /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If -+ /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. -+ TXFF OFFSET(5) NUMBITS(1) [], -+ -+ /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the -+ /// UARTLCR_H Register. -+ /// -+ /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If -+ /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. -+ RXFE OFFSET(4) NUMBITS(1) [] -+ ], -+ -+ /// Integer Baud rate divisor -+ IBRD [ -+ /// Integer Baud rate divisor -+ IBRD OFFSET(0) NUMBITS(16) [] -+ ], -+ -+ /// Fractional Baud rate divisor -+ FBRD [ -+ /// Fractional Baud rate divisor -+ FBRD OFFSET(0) NUMBITS(6) [] -+ ], -+ -+ /// Line Control register -+ LCRH [ -+ /// Word length. These bits indicate the number of data bits transmitted or received in a -+ /// frame. -+ WLEN OFFSET(5) NUMBITS(2) [ -+ FiveBit = 0b00, -+ SixBit = 0b01, -+ SevenBit = 0b10, -+ EightBit = 0b11 -+ ], -+ -+ /// Enable FIFOs: -+ /// -+ /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding -+ /// registers -+ /// -+ /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). -+ FEN OFFSET(4) NUMBITS(1) [ -+ FifosDisabled = 0, -+ FifosEnabled = 1 -+ ] -+ ], -+ -+ /// Control Register -+ CR [ -+ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. -+ /// Data reception occurs for UART signals. When the UART is disabled in the middle of -+ /// reception, it completes the current character before stopping. -+ RXE OFFSET(9) NUMBITS(1) [ -+ Disabled = 0, -+ Enabled = 1 -+ ], -+ -+ /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. -+ /// Data transmission occurs for UART signals. When the UART is disabled in the middle of -+ /// transmission, it completes the current character before stopping. -+ TXE OFFSET(8) NUMBITS(1) [ -+ Disabled = 0, -+ Enabled = 1 -+ ], -+ -+ /// UART enable -+ UARTEN OFFSET(0) NUMBITS(1) [ -+ /// If the UART is disabled in the middle of transmission or reception, it completes the -+ /// current character before stopping. -+ Disabled = 0, -+ Enabled = 1 -+ ] -+ ], -+ -+ /// Interrupt Clear Register -+ ICR [ -+ /// Meta field for all pending interrupts -+ ALL OFFSET(0) NUMBITS(11) [] -+ ] -+} -+ -+register_structs! { -+ #[allow(non_snake_case)] -+ pub RegisterBlock { -+ (0x00 => DR: ReadWrite), -+ (0x04 => _reserved1), -+ (0x18 => FR: ReadOnly), -+ (0x1c => _reserved2), -+ (0x24 => IBRD: WriteOnly), -+ (0x28 => FBRD: WriteOnly), -+ (0x2c => LCRH: WriteOnly), -+ (0x30 => CR: WriteOnly), -+ (0x34 => _reserved3), -+ (0x44 => ICR: WriteOnly), -+ (0x48 => @END), -+ } -+} -+ -+/// Abstraction for the associated MMIO registers. -+type Registers = MMIODerefWrapper; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+pub struct PL011UartInner { -+ registers: Registers, -+ chars_written: usize, -+ chars_read: usize, -+} -+ -+// Export the inner struct so that BSPs can use it for the panic handler. -+pub use PL011UartInner as PanicUart; -+ -+/// Representation of the UART. -+pub struct PL011Uart { -+ inner: NullLock, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl PL011UartInner { -+ /// Create an instance. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ Self { -+ registers: Registers::new(mmio_start_addr), -+ chars_written: 0, -+ chars_read: 0, -+ } -+ } -+ -+ /// Set up baud rate and characteristics. -+ /// -+ /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: -+ /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` -+ /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best -+ /// approximation we can get. A 5 modulo error margin is acceptable for UART and we're now at 0,01 modulo. -+ /// -+ /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). -+ pub fn init(&mut self) { -+ // Turn it off temporarily. -+ self.registers.CR.set(0); -+ -+ self.registers.ICR.write(ICR::ALL::CLEAR); -+ self.registers.IBRD.write(IBRD::IBRD.val(13)); -+ self.registers.FBRD.write(FBRD::FBRD.val(1)); -+ self.registers -+ .LCRH -+ .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on -+ self.registers -+ .CR -+ .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); -+ } -+ -+ /// Send a character. -+ fn write_char(&mut self, c: char) { -+ // Spin while TX FIFO full is set, waiting for an empty slot. -+ while self.registers.FR.matches_all(FR::TXFF::SET) { -+ cpu::nop(); -+ } -+ -+ // Write the character to the buffer. -+ self.registers.DR.set(c as u32); -+ -+ self.chars_written += 1; -+ } -+} -+ -+/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -+/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -+/// we get `write_fmt()` automatically. -+/// -+/// The function takes an `&mut self`, so it must be implemented for the inner struct. -+/// -+/// See [`src/print.rs`]. -+/// -+/// [`src/print.rs`]: ../../print/index.html -+impl fmt::Write for PL011UartInner { -+ fn write_str(&mut self, s: &str) -> fmt::Result { -+ for c in s.chars() { -+ self.write_char(c); -+ } -+ -+ Ok(()) -+ } -+} -+ -+impl PL011Uart { -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ Self { -+ inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), -+ } -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+use synchronization::interface::Mutex; -+ -+impl driver::interface::DeviceDriver for PL011Uart { -+ fn compatible(&self) -> &'static str { -+ "BCM PL011 UART" -+ } -+ -+ unsafe fn init(&self) -> Result<(), &'static str> { -+ self.inner.lock(|inner| inner.init()); -+ -+ Ok(()) -+ } -+} -+ -+impl console::interface::Write for PL011Uart { -+ /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to -+ /// serialize access. -+ fn write_char(&self, c: char) { -+ self.inner.lock(|inner| inner.write_char(c)); -+ } -+ -+ fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { -+ // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase -+ // readability. -+ self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) -+ } -+} -+ -+impl console::interface::Read for PL011Uart { -+ fn read_char(&self) -> char { -+ self.inner.lock(|inner| { -+ // Spin while RX FIFO empty is set. -+ while inner.registers.FR.matches_all(FR::RXFE::SET) { -+ cpu::nop(); -+ } -+ -+ // Read one character. -+ let mut ret = inner.registers.DR.get() as u8 as char; -+ -+ // Convert carrige return to newline. -+ if ret == '\r' { -+ ret = '\n' -+ } -+ -+ // Update statistics. -+ inner.chars_read += 1; -+ -+ ret -+ }) -+ } -+} -+ -+impl console::interface::Statistics for PL011Uart { -+ fn chars_written(&self) -> usize { -+ self.inner.lock(|inner| inner.chars_written) -+ } -+ -+ fn chars_read(&self) -> usize { -+ self.inner.lock(|inner| inner.chars_read) -+ } -+} - -diff -uNr 05_safe_globals/src/bsp/device_driver/bcm.rs 06_drivers_gpio_uart/src/bsp/device_driver/bcm.rs ---- 05_safe_globals/src/bsp/device_driver/bcm.rs -+++ 06_drivers_gpio_uart/src/bsp/device_driver/bcm.rs -@@ -0,0 +1,11 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! BCM driver top level. -+ -+mod bcm2xxx_gpio; -+mod bcm2xxx_pl011_uart; -+ -+pub use bcm2xxx_gpio::*; -+pub use bcm2xxx_pl011_uart::*; - -diff -uNr 05_safe_globals/src/bsp/device_driver/common.rs 06_drivers_gpio_uart/src/bsp/device_driver/common.rs ---- 05_safe_globals/src/bsp/device_driver/common.rs -+++ 06_drivers_gpio_uart/src/bsp/device_driver/common.rs -@@ -0,0 +1,38 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Common device driver code. -+ -+use core::{marker::PhantomData, ops}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+pub struct MMIODerefWrapper { -+ start_addr: usize, -+ phantom: PhantomData T>, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl MMIODerefWrapper { -+ /// Create an instance. -+ pub const unsafe fn new(start_addr: usize) -> Self { -+ Self { -+ start_addr, -+ phantom: PhantomData, -+ } -+ } -+} -+ -+impl ops::Deref for MMIODerefWrapper { -+ type Target = T; -+ -+ fn deref(&self) -> &Self::Target { -+ unsafe { &*(self.start_addr as *const _) } -+ } -+} - -diff -uNr 05_safe_globals/src/bsp/device_driver.rs 06_drivers_gpio_uart/src/bsp/device_driver.rs ---- 05_safe_globals/src/bsp/device_driver.rs -+++ 06_drivers_gpio_uart/src/bsp/device_driver.rs -@@ -0,0 +1,12 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Device driver. -+ -+#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -+mod bcm; -+mod common; -+ -+#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -+pub use bcm::*; - -diff -uNr 05_safe_globals/src/bsp/raspberrypi/console.rs 06_drivers_gpio_uart/src/bsp/raspberrypi/console.rs ---- 05_safe_globals/src/bsp/raspberrypi/console.rs -+++ 06_drivers_gpio_uart/src/bsp/raspberrypi/console.rs -@@ -4,113 +4,34 @@ - - //! BSP console facilities. - --use crate::{console, synchronization, synchronization::NullLock}; -+use super::memory; -+use crate::{bsp::device_driver, console}; - use core::fmt; - - //-------------------------------------------------------------------------------------------------- --// Private Definitions -+// Public Code - //-------------------------------------------------------------------------------------------------- - --/// A mystical, magical device for generating QEMU output out of the void. -+/// In case of a panic, the panic handler uses this function to take a last shot at printing -+/// something before the system is halted. - /// --/// The mutex protected part. --struct QEMUOutputInner { -- chars_written: usize, --} -- --//-------------------------------------------------------------------------------------------------- --// Public Definitions --//-------------------------------------------------------------------------------------------------- -- --/// The main struct. --pub struct QEMUOutput { -- inner: NullLock, --} -- --//-------------------------------------------------------------------------------------------------- --// Global instances --//-------------------------------------------------------------------------------------------------- -- --static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); -- --//-------------------------------------------------------------------------------------------------- --// Private Code --//-------------------------------------------------------------------------------------------------- -- --impl QEMUOutputInner { -- const fn new() -> QEMUOutputInner { -- QEMUOutputInner { chars_written: 0 } -- } -- -- /// Send a character. -- fn write_char(&mut self, c: char) { -- unsafe { -- core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); -- } -- -- self.chars_written += 1; -- } --} -- --/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are --/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, --/// we get `write_fmt()` automatically. -+/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -+/// with synchronization primitives, which increases chances that we get to print something, even -+/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. - /// --/// The function takes an `&mut self`, so it must be implemented for the inner struct. -+/// # Safety - /// --/// See [`src/print.rs`]. --/// --/// [`src/print.rs`]: ../../print/index.html --impl fmt::Write for QEMUOutputInner { -- fn write_str(&mut self, s: &str) -> fmt::Result { -- for c in s.chars() { -- // Convert newline to carrige return + newline. -- if c == '\n' { -- self.write_char('\r') -- } -- -- self.write_char(c); -- } -- -- Ok(()) -- } --} -- --//-------------------------------------------------------------------------------------------------- --// Public Code --//-------------------------------------------------------------------------------------------------- -- --impl QEMUOutput { -- /// Create a new instance. -- pub const fn new() -> QEMUOutput { -- QEMUOutput { -- inner: NullLock::new(QEMUOutputInner::new()), -- } -- } -+/// - Use only for printing during a panic. -+pub unsafe fn panic_console_out() -> impl fmt::Write { -+ let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); -+ let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); -+ -+ panic_gpio.map_pl011_uart(); -+ panic_uart.init(); -+ panic_uart - } - - /// Return a reference to the console. - pub fn console() -> &'static impl console::interface::All { -- &QEMU_OUTPUT --} -- --//------------------------------------------------------------------------------ --// OS Interface Code --//------------------------------------------------------------------------------ --use synchronization::interface::Mutex; -- --/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to --/// serialize access. --impl console::interface::Write for QEMUOutput { -- fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { -- // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase -- // readability. -- self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) -- } --} -- --impl console::interface::Statistics for QEMUOutput { -- fn chars_written(&self) -> usize { -- self.inner.lock(|inner| inner.chars_written) -- } -+ &super::PL011_UART - } - -diff -uNr 05_safe_globals/src/bsp/raspberrypi/driver.rs 06_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs ---- 05_safe_globals/src/bsp/raspberrypi/driver.rs -+++ 06_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs -@@ -0,0 +1,49 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! BSP driver support. -+ -+use crate::driver; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Device Driver Manager type. -+struct BSPDriverManager { -+ device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Global instances -+//-------------------------------------------------------------------------------------------------- -+ -+static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { -+ device_drivers: [&super::GPIO, &super::PL011_UART], -+}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return a reference to the driver manager. -+pub fn driver_manager() -> &'static impl driver::interface::DriverManager { -+ &BSP_DRIVER_MANAGER -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+use driver::interface::DeviceDriver; -+ -+impl driver::interface::DriverManager for BSPDriverManager { -+ fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { -+ &self.device_drivers[..] -+ } -+ -+ fn post_device_driver_init(&self) { -+ // Configure PL011Uart's output pins. -+ super::GPIO.map_pl011_uart(); -+ } -+} - -diff -uNr 05_safe_globals/src/bsp/raspberrypi/memory.rs 06_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs ---- 05_safe_globals/src/bsp/raspberrypi/memory.rs -+++ 06_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs -@@ -24,6 +24,29 @@ - #[rustfmt::skip] - pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; -+ -+ pub const GPIO_OFFSET: usize = 0x0020_0000; -+ pub const UART_OFFSET: usize = 0x0020_1000; -+ -+ /// Physical devices. -+ #[cfg(feature = "bsp_rpi3")] -+ pub mod mmio { -+ use super::*; -+ -+ pub const START: usize = 0x3F00_0000; -+ pub const GPIO_START: usize = START + GPIO_OFFSET; -+ pub const PL011_UART_START: usize = START + UART_OFFSET; -+ } -+ -+ /// Physical devices. -+ #[cfg(feature = "bsp_rpi4")] -+ pub mod mmio { -+ use super::*; -+ -+ pub const START: usize = 0xFE00_0000; -+ pub const GPIO_START: usize = START + GPIO_OFFSET; -+ pub const PL011_UART_START: usize = START + UART_OFFSET; -+ } - } - - //-------------------------------------------------------------------------------------------------- - -diff -uNr 05_safe_globals/src/bsp/raspberrypi.rs 06_drivers_gpio_uart/src/bsp/raspberrypi.rs ---- 05_safe_globals/src/bsp/raspberrypi.rs -+++ 06_drivers_gpio_uart/src/bsp/raspberrypi.rs -@@ -6,4 +6,33 @@ - - pub mod console; - pub mod cpu; -+pub mod driver; - pub mod memory; -+ -+//-------------------------------------------------------------------------------------------------- -+// Global instances -+//-------------------------------------------------------------------------------------------------- -+use super::device_driver; -+ -+static GPIO: device_driver::GPIO = -+ unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; -+ -+static PL011_UART: device_driver::PL011Uart = -+ unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Board identification. -+pub fn board_name() -> &'static str { -+ #[cfg(feature = "bsp_rpi3")] -+ { -+ "Raspberry Pi 3" -+ } -+ -+ #[cfg(feature = "bsp_rpi4")] -+ { -+ "Raspberry Pi 4" -+ } -+} - -diff -uNr 05_safe_globals/src/bsp.rs 06_drivers_gpio_uart/src/bsp.rs ---- 05_safe_globals/src/bsp.rs -+++ 06_drivers_gpio_uart/src/bsp.rs -@@ -4,6 +4,8 @@ - - //! Conditional re-exporting of Board Support Packages. - -+mod device_driver; -+ - #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] - mod raspberrypi; - - -diff -uNr 05_safe_globals/src/console.rs 06_drivers_gpio_uart/src/console.rs ---- 05_safe_globals/src/console.rs -+++ 06_drivers_gpio_uart/src/console.rs -@@ -14,18 +14,34 @@ - - /// Console write functions. - pub trait Write { -+ /// Write a single character. -+ fn write_char(&self, c: char); -+ - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - } - -+ /// Console read functions. -+ pub trait Read { -+ /// Read a single character. -+ fn read_char(&self) -> char { -+ ' ' -+ } -+ } -+ - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } -+ -+ /// Return the number of characters read. -+ fn chars_read(&self) -> usize { -+ 0 -+ } - } - - /// Trait alias for a full-fledged console. -- pub trait All = Write + Statistics; -+ pub trait All = Write + Read + Statistics; - } - -diff -uNr 05_safe_globals/src/driver.rs 06_drivers_gpio_uart/src/driver.rs ---- 05_safe_globals/src/driver.rs -+++ 06_drivers_gpio_uart/src/driver.rs -@@ -0,0 +1,44 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Driver support. -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Driver interfaces. -+pub mod interface { -+ /// Device Driver functions. -+ pub trait DeviceDriver { -+ /// Return a compatibility string for identifying the driver. -+ fn compatible(&self) -> &'static str; -+ -+ /// Called by the kernel to bring up the device. -+ /// -+ /// # Safety -+ /// -+ /// - During init, drivers might do stuff with system-wide impact. -+ unsafe fn init(&self) -> Result<(), &'static str> { -+ Ok(()) -+ } -+ } -+ -+ /// Device driver management functions. -+ /// -+ /// The `BSP` is supposed to supply one global instance. -+ pub trait DriverManager { -+ /// Return a slice of references to all `BSP`-instantiated drivers. -+ /// -+ /// # Safety -+ /// -+ /// - The order of devices is the order in which `DeviceDriver::init()` is called. -+ fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; -+ -+ /// Initialization code that runs after driver init. -+ /// -+ /// For example, device driver code that depends on other drivers already being online. -+ fn post_device_driver_init(&self); -+ } -+} - -diff -uNr 05_safe_globals/src/main.rs 06_drivers_gpio_uart/src/main.rs ---- 05_safe_globals/src/main.rs -+++ 06_drivers_gpio_uart/src/main.rs -@@ -7,6 +7,14 @@ - - //! The `kernel` binary. - //! -+//! # TL;DR - Overview of important Kernel entities -+//! -+//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -+//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -+//! -+//! [console interface]: ../libkernel/console/interface/index.html -+//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -+//! - //! # Code organization and architecture - //! - //! The code is divided into different *modules*, each representing a typical **subsystem** of the -@@ -92,6 +100,7 @@ - //! - `crate::memory::*` - //! - `crate::bsp::memory::*` - -+#![feature(const_fn_fn_ptr_basics)] - #![feature(format_args_nl)] - #![feature(naked_functions)] - #![feature(panic_info_message)] -@@ -105,6 +114,7 @@ - mod bsp; - mod console; - mod cpu; -+mod driver; - mod memory; - mod panic_wait; - mod print; -@@ -116,16 +126,53 @@ - /// # Safety - /// - /// - Only a single core must be active and running this function. -+/// - The init calls in this function must appear in the correct order. - unsafe fn kernel_init() -> ! { -- use console::interface::Statistics; -+ use driver::interface::DriverManager; -+ -+ for i in bsp::driver::driver_manager().all_device_drivers().iter() { -+ if let Err(x) = i.init() { -+ panic!("Error loading driver: {}: {}", i.compatible(), x); -+ } -+ } -+ bsp::driver::driver_manager().post_device_driver_init(); -+ // println! is usable from here on. -+ -+ // Transition from unsafe to safe. -+ kernel_main() -+} - -- println!("[0] Hello from pure Rust!"); -+/// The main function running after the early init. -+fn kernel_main() -> ! { -+ use console::interface::All; -+ use driver::interface::DriverManager; -+ -+ // Wait for user to hit Enter. -+ loop { -+ if bsp::console::console().read_char() == '\n' { -+ break; -+ } -+ } -+ -+ println!("[0] Booting on: {}", bsp::board_name()); -+ -+ println!("[1] Drivers loaded:"); -+ for (i, driver) in bsp::driver::driver_manager() -+ .all_device_drivers() -+ .iter() -+ .enumerate() -+ { -+ println!(" {}. {}", i + 1, driver.compatible()); -+ } - - println!( -- "[1] Chars written: {}", -+ "[2] Chars written: {}", - bsp::console::console().chars_written() - ); -+ println!("[3] Echoing input now"); - -- println!("[2] Stopping here."); -- cpu::wait_forever() -+ loop { -+ let c = bsp::console::console().read_char(); -+ bsp::console::console().write_char(c); -+ } - } - -diff -uNr 05_safe_globals/src/panic_wait.rs 06_drivers_gpio_uart/src/panic_wait.rs ---- 05_safe_globals/src/panic_wait.rs -+++ 06_drivers_gpio_uart/src/panic_wait.rs -@@ -4,15 +4,35 @@ - - //! A panic handler that infinitely waits. - --use crate::{cpu, println}; --use core::panic::PanicInfo; -+use crate::{bsp, cpu}; -+use core::{fmt, panic::PanicInfo}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+fn _panic_print(args: fmt::Arguments) { -+ use fmt::Write; -+ -+ unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -+} -+ -+/// Prints with a newline - only use from the panic handler. -+/// -+/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -+#[macro_export] -+macro_rules! panic_println { -+ ($($arg:tt)*) => ({ -+ _panic_print(format_args_nl!($($arg)*)); -+ }) -+} - - #[panic_handler] - fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { -- println!("\nKernel panic: {}", args); -+ panic_println!("\nKernel panic: {}", args); - } else { -- println!("\nKernel panic!"); -+ panic_println!("\nKernel panic!"); - } - - cpu::wait_forever() - -``` diff --git a/06_drivers_gpio_uart/build.rs b/06_drivers_gpio_uart/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/06_drivers_gpio_uart/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/06_drivers_gpio_uart/src/_arch/aarch64/cpu.rs b/06_drivers_gpio_uart/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 53f131f88..000000000 --- a/06_drivers_gpio_uart/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - use crate::runtime_init; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); - runtime_init::runtime_init() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Spin for `n` cycles. -#[cfg(feature = "bsp_rpi3")] -#[inline(always)] -pub fn spin_for_cycles(n: usize) { - for _ in 0..n { - asm::nop(); - } -} - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} diff --git a/06_drivers_gpio_uart/src/_arch/aarch64/cpu/smp.rs b/06_drivers_gpio_uart/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/06_drivers_gpio_uart/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/06_drivers_gpio_uart/src/bsp.rs b/06_drivers_gpio_uart/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/06_drivers_gpio_uart/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/06_drivers_gpio_uart/src/bsp/device_driver.rs b/06_drivers_gpio_uart/src/bsp/device_driver.rs deleted file mode 100644 index ce7396f22..000000000 --- a/06_drivers_gpio_uart/src/bsp/device_driver.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/06_drivers_gpio_uart/src/bsp/device_driver/bcm.rs b/06_drivers_gpio_uart/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 59071d5d8..000000000 --- a/06_drivers_gpio_uart/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index f5abbee8a..000000000 --- a/06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,221 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::cpu; - - // Make an educated guess for a good delay value (Sequence described in the BCM2837 - // peripherals PDF). - // - // - According to Wikipedia, the fastest Pi3 clocks around 1.4 GHz. - // - The Linux 2837 GPIO driver waits 1 µs between the steps. - // - // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs - // would the CPU be clocked at 2 GHz. - const DELAY: usize = 2000; - - self.registers.GPPUD.write(GPPUD::PUD::Off); - cpu::spin_for_cycles(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - cpu::spin_for_cycles(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index f17a51ece..000000000 --- a/06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,305 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => _reserved3), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Read one character. - let mut ret = inner.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - inner.chars_read += 1; - - ret - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} diff --git a/06_drivers_gpio_uart/src/bsp/device_driver/common.rs b/06_drivers_gpio_uart/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/06_drivers_gpio_uart/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/06_drivers_gpio_uart/src/bsp/raspberrypi.rs b/06_drivers_gpio_uart/src/bsp/raspberrypi.rs deleted file mode 100644 index 10888d37f..000000000 --- a/06_drivers_gpio_uart/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/06_drivers_gpio_uart/src/bsp/raspberrypi/console.rs b/06_drivers_gpio_uart/src/bsp/raspberrypi/console.rs deleted file mode 100644 index d1b60dd82..000000000 --- a/06_drivers_gpio_uart/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} diff --git a/06_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs b/06_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/06_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/06_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs b/06_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index fe24dd71b..000000000 --- a/06_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/06_drivers_gpio_uart/src/bsp/raspberrypi/link.ld b/06_drivers_gpio_uart/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/06_drivers_gpio_uart/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/06_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs b/06_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index fae051257..000000000 --- a/06_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/06_drivers_gpio_uart/src/console.rs b/06_drivers_gpio_uart/src/console.rs deleted file mode 100644 index 2644e12c2..000000000 --- a/06_drivers_gpio_uart/src/console.rs +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/06_drivers_gpio_uart/src/cpu.rs b/06_drivers_gpio_uart/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/06_drivers_gpio_uart/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/06_drivers_gpio_uart/src/cpu/smp.rs b/06_drivers_gpio_uart/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/06_drivers_gpio_uart/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/06_drivers_gpio_uart/src/driver.rs b/06_drivers_gpio_uart/src/driver.rs deleted file mode 100644 index e2875b876..000000000 --- a/06_drivers_gpio_uart/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/06_drivers_gpio_uart/src/main.rs b/06_drivers_gpio_uart/src/main.rs deleted file mode 100644 index 4e6840ad1..000000000 --- a/06_drivers_gpio_uart/src/main.rs +++ /dev/null @@ -1,178 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![feature(const_fn_fn_ptr_basics)] -#![feature(format_args_nl)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod driver; -mod memory; -mod panic_wait; -mod print; -mod runtime_init; -mod synchronization; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order. -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use console::interface::All; - use driver::interface::DriverManager; - - // Wait for user to hit Enter. - loop { - if bsp::console::console().read_char() == '\n' { - break; - } - } - - println!("[0] Booting on: {}", bsp::board_name()); - - println!("[1] Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - println!(" {}. {}", i + 1, driver.compatible()); - } - - println!( - "[2] Chars written: {}", - bsp::console::console().chars_written() - ); - println!("[3] Echoing input now"); - - loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); - } -} diff --git a/06_drivers_gpio_uart/src/memory.rs b/06_drivers_gpio_uart/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/06_drivers_gpio_uart/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/06_drivers_gpio_uart/src/panic_wait.rs b/06_drivers_gpio_uart/src/panic_wait.rs deleted file mode 100644 index 1386e1e23..000000000 --- a/06_drivers_gpio_uart/src/panic_wait.rs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/06_drivers_gpio_uart/src/print.rs b/06_drivers_gpio_uart/src/print.rs deleted file mode 100644 index 77ebd8b40..000000000 --- a/06_drivers_gpio_uart/src/print.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} diff --git a/06_drivers_gpio_uart/src/runtime_init.rs b/06_drivers_gpio_uart/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/06_drivers_gpio_uart/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/06_drivers_gpio_uart/src/synchronization.rs b/06_drivers_gpio_uart/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/06_drivers_gpio_uart/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/06_uart_chainloader/.vscode/settings.json b/06_uart_chainloader/.vscode/settings.json new file mode 100644 index 000000000..bfa278e9a --- /dev/null +++ b/06_uart_chainloader/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/06_uart_chainloader/Cargo.lock b/06_uart_chainloader/Cargo.lock new file mode 100644 index 000000000..047875fe5 --- /dev/null +++ b/06_uart_chainloader/Cargo.lock @@ -0,0 +1,26 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.6.0" +dependencies = [ + "aarch64-cpu", + "tock-registers", +] + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/06_uart_chainloader/Cargo.toml b/06_uart_chainloader/Cargo.toml new file mode 100644 index 000000000..27b413a28 --- /dev/null +++ b/06_uart_chainloader/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "mingo" +version = "0.6.0" +authors = ["Andre Richter "] +edition = "2021" + +[profile.release] +lto = true + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] + +[[bin]] +name = "kernel" +path = "src/main.rs" + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/06_uart_chainloader/Makefile b/06_uart_chainloader/Makefile new file mode 100644 index 000000000..3366de31d --- /dev/null +++ b/06_uart_chainloader/Makefile @@ -0,0 +1,246 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 + CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 + CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_MINIPUSH = ruby tests/chainboot_test.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DEV = --privileged -v /dev:/dev + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu qemuasm: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +qemuasm: $(KERNEL_BIN) + $(call color_header, "Launching QEMU with ASM output") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_MINIPUSH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) \ + -kernel $(KERNEL_BIN) $(CHAINBOOT_DEMO_PAYLOAD) + +test: test_boot + +endif diff --git a/06_uart_chainloader/README.CN.md b/06_uart_chainloader/README.CN.md new file mode 100644 index 000000000..de7f51114 --- /dev/null +++ b/06_uart_chainloader/README.CN.md @@ -0,0 +1,116 @@ +# 教程06 - UART链加载器 + +## tl;dr + +- 从SD卡上运行是一次不错的体验,但是每次都为每个新的二进制文件这样做将非常繁琐。 + 因此,让我们编写一个[chainloader]。 +- 这将是您需要放在SD卡上的最后一个二进制文件。 + 每个后续的教程都将在`Makefile`中提供一个`chainboot`,让您方便地通过`UART`加载内核。 + +[chainloader]: https://en.wikipedia.org/wiki/Chain_loading + + +## 注意 + +请注意,这个教程中有一些内容仅通过查看源代码很难理解。 + +大致的意思是,在`boot.s`中,我们编写了一段[position independent code]代码, +它会自动确定固件加载二进制文件的位置(`0x8_0000`),以及链接到的位置(`0x200_0000`,参见 `kernel.ld`)。 +然后,二进制文件将自身从加载地址复制到链接地址(也就是"重定位"自身),然后跳转到`_start_rust()`的重定位版本。 + +由于链加载程序现在已经"脱离了路径",它现在可以从`UART`接收另一个内核二进制文件,并将其复制到RPi固件的标准加载地址`0x8_0000`。 +最后,它跳转到`0x8_0000`,新加载的二进制文件会透明地执行,就好像它一直从SD卡加载一样。 + +在我有时间详细写下这些内容之前,请耐心等待。目前,请将这个教程视为一种便利功能的启用程序,它允许快速启动以下教程。 +_对于那些渴望深入了解的人,可以直接跳到第[15章](../15_virtual_mem_part3_precomputed_tables),阅读README的前半部分, +其中讨论了`Load Address != Link Address`的问题_。 + +[position independent code]: https://en.wikipedia.org/wiki/Position-independent_code + +## 安装并测试它 + +我们的链加载程序称为`MiniLoad`,受到了[raspbootin]的启发。 + +您可以按照以下教程尝试它: +1. 根据您的目标硬件运行命令:`make`或`BSP=rpi4 make`。 +1. 将`kernel8.img`复制到SD卡中,并将SD卡重新插入您的RPi。 +1. 运行命令`make chainboot`或`BSP=rpi4 make chainboot`。 +1. 将USB串口连接到您的主机PC上。 + - 请参考[top-level README](../README.md#-usb-serial-output)中的接线图。 + - 确保您**没有**连接USB串口的电源引脚,只连接RX/TX和GND。 +1. 将RPi连接到(USB)电源线。 +1. 观察加载程序通过`UART`获取内核: + +> ❗ **注意**: `make chainboot`假设默认的串行设备名称为`/dev/ttyUSB0`。根据您的主机操作系统,设备名称可能会有所不同。 +> 例如,在`macOS`上,它可能是类似于`/dev/tty.usbserial-0001`的名称。 +> 在这种情况下,请明确给出设备名称: + + +```console +$ DEV_SERIAL=/dev/tty.usbserial-0001 make chainboot +``` + +[raspbootin]: https://github.com/mrvn/raspbootin + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 7 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[0] mingo version 0.5.0 +[1] Booting on: Raspberry Pi 3 +[2] Drivers loaded: + 1. BCM PL011 UART + 2. BCM GPIO +[3] Chars written: 117 +[4] Echoing input now +``` + +在这个教程中,为了演示目的,加载了上一个教程中的内核版本。在后续的教程中,将使用工作目录的内核。 + +## 测试它 + +这个教程中的`Makefile`有一个额外的目标`qemuasm`,它可以让你很好地观察到内核在重新定位后如何从加载地址区域(`0x80_XXX`) +跳转到重新定位的代码(`0x0200_0XXX`): + +```console +$ make qemuasm +[...] +N: +0x00080030: 58000140 ldr x0, #0x80058 +0x00080034: 9100001f mov sp, x0 +0x00080038: 58000141 ldr x1, #0x80060 +0x0008003c: d61f0020 br x1 + +---------------- +IN: +0x02000070: 9400044c bl #0x20011a0 + +---------------- +IN: +0x020011a0: 90000008 adrp x8, #0x2001000 +0x020011a4: 90000009 adrp x9, #0x2001000 +0x020011a8: f9446508 ldr x8, [x8, #0x8c8] +0x020011ac: f9446929 ldr x9, [x9, #0x8d0] +0x020011b0: eb08013f cmp x9, x8 +0x020011b4: 54000109 b.ls #0x20011d4 +[...] +``` + +## 相比之前的变化(diff) +请检查[英文版本](README.md#diff-to-previous),这是最新的。 \ No newline at end of file diff --git a/06_uart_chainloader/README.md b/06_uart_chainloader/README.md new file mode 100644 index 000000000..5e4efe25d --- /dev/null +++ b/06_uart_chainloader/README.md @@ -0,0 +1,670 @@ +# Tutorial 06 - UART Chainloader + +## tl;dr + +- Running from an SD card was a nice experience, but it would be extremely tedious to do it for + every new binary. So let's write a [chainloader]. +- This will be the last binary you need to put on the SD card. Each following tutorial will provide + a `chainboot` target in the `Makefile` that lets you conveniently load the kernel over `UART`. + +[chainloader]: https://en.wikipedia.org/wiki/Chain_loading + + +## Note + +Please note that there is stuff going on in this tutorial that is very hard to grasp by only looking +at the source code changes. + +The gist of it is that in `boot.s`, we are writing a piece of [position independent code] which +automatically determines where the firmware has loaded the binary (`0x8_0000`), and where it was +linked to (`0x200_0000`, see `kernel.ld`). The binary then copies itself from loaded to linked +address (aka "relocating" itself), and then jumps to the relocated version of `_start_rust()`. + +Since the chainloader has put itself "out of the way" now, it can now receive another kernel binary +from the `UART` and copy it to the standard load address of the RPi firmware at `0x8_0000`. Finally, +it jumps to `0x8_0000` and the newly loaded binary transparently executes as if it had been loaded +from SD card all along. + +Please bear with me until I find the time to write it all down here elaborately. For the time being, +please see this tutorial as an enabler for a convenience feature that allows booting the following +tutorials in a quick manner. _For those keen to get a deeper understanding, it could make sense to +skip forward to [Chapter 15](../15_virtual_mem_part3_precomputed_tables) and read the first half of +the README, where `Load Address != Link Address` is discussed_. + +[position independent code]: https://en.wikipedia.org/wiki/Position-independent_code + +## Install and test it + +Our chainloader is called `MiniLoad` and is inspired by [raspbootin]. + +You can try it with this tutorial already: +1. Depending on your target hardware, run:`make` or `BSP=rpi4 make`. +1. Copy `kernel8.img` to the SD card and put the SD card back into your RPi. +1. Run `make chainboot` or `BSP=rpi4 make chainboot`. +1. Connect the USB serial to your host PC. + - Wiring diagram at [top-level README](../README.md#-usb-serial-output). + - Make sure that you **DID NOT** connect the power pin of the USB serial. Only RX/TX and GND. +1. Connect the RPi to the (USB) power cable. +1. Observe the loader fetching a kernel over `UART`: + +> ❗ **NOTE**: `make chainboot` assumes a default serial device name of `/dev/ttyUSB0`. Depending on +> your host operating system, the device name might differ. For example, on `macOS`, it might be +> something like `/dev/tty.usbserial-0001`. In this case, please give the name explicitly: + + +```console +$ DEV_SERIAL=/dev/tty.usbserial-0001 make chainboot +``` + +[raspbootin]: https://github.com/mrvn/raspbootin + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 7 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[0] mingo version 0.5.0 +[1] Booting on: Raspberry Pi 3 +[2] Drivers loaded: + 1. BCM PL011 UART + 2. BCM GPIO +[3] Chars written: 117 +[4] Echoing input now +``` + +In this tutorial, a version of the kernel from the previous tutorial is loaded for demo purposes. In +subsequent tutorials, it will be the working directory's kernel. + +## Test it + +The `Makefile` in this tutorial has an additional target, `qemuasm`, that lets you nicely observe +how the kernel, after relocating itself, jumps the load address region (`0x80_XXX`) to the relocated +code at (`0x0200_0XXX`): + +```console +$ make qemuasm +[...] +N: +0x00080030: 58000140 ldr x0, #0x80058 +0x00080034: 9100001f mov sp, x0 +0x00080038: 58000141 ldr x1, #0x80060 +0x0008003c: d61f0020 br x1 + +---------------- +IN: +0x02000070: 9400044c bl #0x20011a0 + +---------------- +IN: +0x020011a0: 90000008 adrp x8, #0x2001000 +0x020011a4: 90000009 adrp x9, #0x2001000 +0x020011a8: f9446508 ldr x8, [x8, #0x8c8] +0x020011ac: f9446929 ldr x9, [x9, #0x8d0] +0x020011b0: eb08013f cmp x9, x8 +0x020011b4: 54000109 b.ls #0x20011d4 +[...] +``` + +## Diff to previous +```diff + +diff -uNr 05_drivers_gpio_uart/Cargo.toml 06_uart_chainloader/Cargo.toml +--- 05_drivers_gpio_uart/Cargo.toml ++++ 06_uart_chainloader/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.5.0" ++version = "0.6.0" + authors = ["Andre Richter "] + edition = "2021" + +Binary files 05_drivers_gpio_uart/demo_payload_rpi3.img and 06_uart_chainloader/demo_payload_rpi3.img differ +Binary files 05_drivers_gpio_uart/demo_payload_rpi4.img and 06_uart_chainloader/demo_payload_rpi4.img differ + +diff -uNr 05_drivers_gpio_uart/Makefile 06_uart_chainloader/Makefile +--- 05_drivers_gpio_uart/Makefile ++++ 06_uart_chainloader/Makefile +@@ -24,27 +24,29 @@ + QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + + ifeq ($(BSP),rpi3) +- TARGET = aarch64-unknown-none-softfloat +- KERNEL_BIN = kernel8.img +- QEMU_BINARY = qemu-system-aarch64 +- QEMU_MACHINE_TYPE = raspi3 +- QEMU_RELEASE_ARGS = -serial stdio -display none +- OBJDUMP_BINARY = aarch64-none-elf-objdump +- NM_BINARY = aarch64-none-elf-nm +- READELF_BINARY = aarch64-none-elf-readelf +- LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi +- RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 ++ TARGET = aarch64-unknown-none-softfloat ++ KERNEL_BIN = kernel8.img ++ QEMU_BINARY = qemu-system-aarch64 ++ QEMU_MACHINE_TYPE = raspi3 ++ QEMU_RELEASE_ARGS = -serial stdio -display none ++ OBJDUMP_BINARY = aarch64-none-elf-objdump ++ NM_BINARY = aarch64-none-elf-nm ++ READELF_BINARY = aarch64-none-elf-readelf ++ LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi ++ RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 ++ CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img + else ifeq ($(BSP),rpi4) +- TARGET = aarch64-unknown-none-softfloat +- KERNEL_BIN = kernel8.img +- QEMU_BINARY = qemu-system-aarch64 +- QEMU_MACHINE_TYPE = +- QEMU_RELEASE_ARGS = -serial stdio -display none +- OBJDUMP_BINARY = aarch64-none-elf-objdump +- NM_BINARY = aarch64-none-elf-nm +- READELF_BINARY = aarch64-none-elf-readelf +- LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi +- RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 ++ TARGET = aarch64-unknown-none-softfloat ++ KERNEL_BIN = kernel8.img ++ QEMU_BINARY = qemu-system-aarch64 ++ QEMU_MACHINE_TYPE = ++ QEMU_RELEASE_ARGS = -serial stdio -display none ++ OBJDUMP_BINARY = aarch64-none-elf-objdump ++ NM_BINARY = aarch64-none-elf-nm ++ READELF_BINARY = aarch64-none-elf-readelf ++ LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi ++ RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 ++ CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img + endif + + # Export for build.rs. +@@ -90,8 +92,8 @@ + -O binary + + EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +-EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +-EXEC_MINITERM = ruby ../common/serial/miniterm.rb ++EXEC_TEST_MINIPUSH = ruby tests/chainboot_test.rb ++EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + + ##------------------------------------------------------------------------------ + ## Dockerization +@@ -110,7 +112,7 @@ + ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + +- DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) ++ DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + endif + + +@@ -118,7 +120,7 @@ + ##-------------------------------------------------------------------------------------------------- + ## Targets + ##-------------------------------------------------------------------------------------------------- +-.PHONY: all doc qemu miniterm clippy clean readelf objdump nm check ++.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + + all: $(KERNEL_BIN) + +@@ -160,7 +162,7 @@ + ##------------------------------------------------------------------------------ + ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +-qemu: ++qemu qemuasm: + $(call color_header, "$(QEMU_MISSING_STRING)") + + else # QEMU is supported. +@@ -169,13 +171,17 @@ + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + ++qemuasm: $(KERNEL_BIN) ++ $(call color_header, "Launching QEMU with ASM output") ++ @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm ++ + endif + ##------------------------------------------------------------------------------ +-## Connect to the target's serial ++## Push the kernel to the real HW target + ##------------------------------------------------------------------------------ +-miniterm: +- @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) ++chainboot: $(KERNEL_BIN) ++ @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) + + ##------------------------------------------------------------------------------ + ## Run clippy +@@ -232,7 +238,8 @@ + ##------------------------------------------------------------------------------ + test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") +- @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) ++ @$(DOCKER_TEST) $(EXEC_TEST_MINIPUSH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) \ ++ -kernel $(KERNEL_BIN) $(CHAINBOOT_DEMO_PAYLOAD) + + test: test_boot + + +diff -uNr 05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s +--- 05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s ++++ 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s +@@ -18,6 +18,17 @@ + add \register, \register, #:lo12:\symbol + .endm + ++// Load the address of a symbol into a register, absolute. ++// ++// # Resources ++// ++// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html ++.macro ADR_ABS register, symbol ++ movz \register, #:abs_g2:\symbol ++ movk \register, #:abs_g1_nc:\symbol ++ movk \register, #:abs_g0_nc:\symbol ++.endm ++ + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -37,23 +48,35 @@ + // If execution reaches here, it is the boot core. + + // Initialize DRAM. +- ADR_REL x0, __bss_start +- ADR_REL x1, __bss_end_exclusive ++ ADR_ABS x0, __bss_start ++ ADR_ABS x1, __bss_end_exclusive + + .L_bss_init_loop: + cmp x0, x1 +- b.eq .L_prepare_rust ++ b.eq .L_relocate_binary + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + ++ // Next, relocate the binary. ++.L_relocate_binary: ++ ADR_REL x0, __binary_nonzero_start // The address the binary got loaded to. ++ ADR_ABS x1, __binary_nonzero_start // The address the binary was linked to. ++ ADR_ABS x2, __binary_nonzero_end_exclusive ++ ++.L_copy_loop: ++ ldr x3, [x0], #8 ++ str x3, [x1], #8 ++ cmp x1, x2 ++ b.lo .L_copy_loop ++ + // Prepare the jump to Rust code. +-.L_prepare_rust: + // Set the stack pointer. +- ADR_REL x0, __boot_core_stack_end_exclusive ++ ADR_ABS x0, __boot_core_stack_end_exclusive + mov sp, x0 + +- // Jump to Rust code. +- b _start_rust ++ // Jump to the relocated Rust code. ++ ADR_ABS x1, _start_rust ++ br x1 + + // Infinitely wait for events (aka "park the core"). + .L_parking_loop: + +diff -uNr 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +--- 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ++++ 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +@@ -275,7 +275,7 @@ + } + + /// Retrieve a character. +- fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { ++ fn read_char(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. +@@ -290,12 +290,7 @@ + } + + // Read one character. +- let mut ret = self.registers.DR.get() as u8 as char; +- +- // Convert carrige return to newline. +- if ret == '\r' { +- ret = '\n' +- } ++ let ret = self.registers.DR.get() as u8 as char; + + // Update statistics. + self.chars_read += 1; +@@ -381,14 +376,14 @@ + impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner +- .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) ++ .lock(|inner| inner.read_char(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner +- .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) ++ .lock(|inner| inner.read_char(BlockingMode::NonBlocking)) + .is_some() + {} + } + +diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs 06_uart_chainloader/src/bsp/raspberrypi/console.rs +--- 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs ++++ 06_uart_chainloader/src/bsp/raspberrypi/console.rs +@@ -1,16 +0,0 @@ +-// SPDX-License-Identifier: MIT OR Apache-2.0 +-// +-// Copyright (c) 2018-2023 Andre Richter +- +-//! BSP console facilities. +- +-use crate::console; +- +-//-------------------------------------------------------------------------------------------------- +-// Public Code +-//-------------------------------------------------------------------------------------------------- +- +-/// Return a reference to the console. +-pub fn console() -> &'static dyn console::interface::All { +- &super::driver::PL011_UART +-} + +diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld +--- 05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld ++++ 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld +@@ -3,8 +3,6 @@ + * Copyright (c) 2018-2023 Andre Richter + */ + +-__rpi_phys_dram_start_addr = 0; +- + /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ + __rpi_phys_binary_load_addr = 0x80000; + +@@ -28,7 +26,8 @@ + + SECTIONS + { +- . = __rpi_phys_dram_start_addr; ++ /* Set the link address to 32 MiB */ ++ . = 0x2000000; + + /*********************************************************************************************** + * Boot Core Stack +@@ -45,6 +44,7 @@ + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ ++ __binary_nonzero_start = .; + .text : + { + KEEP(*(.text._start)) +@@ -60,6 +60,10 @@ + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + ++ /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ ++ . = ALIGN(8); ++ __binary_nonzero_end_exclusive = .; ++ + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + +diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs 06_uart_chainloader/src/bsp/raspberrypi/memory.rs +--- 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs ++++ 06_uart_chainloader/src/bsp/raspberrypi/memory.rs +@@ -11,6 +11,7 @@ + /// The board's physical memory map. + #[rustfmt::skip] + pub(super) mod map { ++ pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; +@@ -35,3 +36,13 @@ + pub const PL011_UART_START: usize = START + UART_OFFSET; + } + } ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// The address on which the Raspberry firmware loads every binary by default. ++#[inline(always)] ++pub fn board_default_load_addr() -> *const u64 { ++ map::BOARD_DEFAULT_LOAD_ADDRESS as _ ++} + +diff -uNr 05_drivers_gpio_uart/src/driver.rs 06_uart_chainloader/src/driver.rs +--- 05_drivers_gpio_uart/src/driver.rs ++++ 06_uart_chainloader/src/driver.rs +@@ -4,10 +4,7 @@ + + //! Driver support. + +-use crate::{ +- println, +- synchronization::{interface::Mutex, NullLock}, +-}; ++use crate::synchronization::{interface::Mutex, NullLock}; + + //-------------------------------------------------------------------------------------------------- + // Private Definitions +@@ -154,14 +151,4 @@ + } + }); + } +- +- /// Enumerate all registered device drivers. +- pub fn enumerate(&self) { +- let mut i: usize = 1; +- self.for_each_descriptor(|descriptor| { +- println!(" {}. {}", i, descriptor.device_driver.compatible()); +- +- i += 1; +- }); +- } + } + +diff -uNr 05_drivers_gpio_uart/src/main.rs 06_uart_chainloader/src/main.rs +--- 05_drivers_gpio_uart/src/main.rs ++++ 06_uart_chainloader/src/main.rs +@@ -142,27 +142,55 @@ + kernel_main() + } + ++const MINILOAD_LOGO: &str = r#" ++ __ __ _ _ _ _ ++| \/ (_)_ _ (_) | ___ __ _ __| | ++| |\/| | | ' \| | |__/ _ \/ _` / _` | ++|_| |_|_|_||_|_|____\___/\__,_\__,_| ++"#; ++ + /// The main function running after the early init. + fn kernel_main() -> ! { + use console::console; + +- println!( +- "[0] {} version {}", +- env!("CARGO_PKG_NAME"), +- env!("CARGO_PKG_VERSION") +- ); +- println!("[1] Booting on: {}", bsp::board_name()); ++ println!("{}", MINILOAD_LOGO); ++ println!("{:^37}", bsp::board_name()); ++ println!(); ++ println!("[ML] Requesting binary"); ++ console().flush(); + +- println!("[2] Drivers loaded:"); +- driver::driver_manager().enumerate(); ++ // Discard any spurious received characters before starting with the loader protocol. ++ console().clear_rx(); + +- println!("[3] Chars written: {}", console().chars_written()); +- println!("[4] Echoing input now"); ++ // Notify `Minipush` to send the binary. ++ for _ in 0..3 { ++ console().write_char(3 as char); ++ } + +- // Discard any spurious received characters before going into echo mode. +- console().clear_rx(); +- loop { +- let c = console().read_char(); +- console().write_char(c); ++ // Read the binary's size. ++ let mut size: u32 = u32::from(console().read_char() as u8); ++ size |= u32::from(console().read_char() as u8) << 8; ++ size |= u32::from(console().read_char() as u8) << 16; ++ size |= u32::from(console().read_char() as u8) << 24; ++ ++ // Trust it's not too big. ++ console().write_char('O'); ++ console().write_char('K'); ++ ++ let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; ++ unsafe { ++ // Read the kernel byte by byte. ++ for i in 0..size { ++ core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) ++ } + } ++ ++ println!("[ML] Loaded! Executing the payload now\n"); ++ console().flush(); ++ ++ // Use black magic to create a function pointer. ++ let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; ++ ++ // Jump to loaded kernel! ++ kernel() + } + +diff -uNr 05_drivers_gpio_uart/tests/boot_test_string.rb 06_uart_chainloader/tests/boot_test_string.rb +--- 05_drivers_gpio_uart/tests/boot_test_string.rb ++++ 06_uart_chainloader/tests/boot_test_string.rb +@@ -1,3 +0,0 @@ +-# frozen_string_literal: true +- +-EXPECTED_PRINT = 'Echoing input now' + +diff -uNr 05_drivers_gpio_uart/tests/chainboot_test.rb 06_uart_chainloader/tests/chainboot_test.rb +--- 05_drivers_gpio_uart/tests/chainboot_test.rb ++++ 06_uart_chainloader/tests/chainboot_test.rb +@@ -0,0 +1,78 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2020-2023 Andre Richter ++ ++require_relative '../../common/serial/minipush' ++require_relative '../../common/tests/boot_test' ++require 'pty' ++ ++# Match for the last print that 'demo_payload_rpiX.img' produces. ++EXPECTED_PRINT = 'Echoing input now' ++ ++# Wait for request to power the target. ++class PowerTargetRequestTest < SubtestBase ++ MINIPUSH_POWER_TARGET_REQUEST = 'Please power the target now' ++ ++ def initialize(qemu_cmd, pty_main) ++ super() ++ @qemu_cmd = qemu_cmd ++ @pty_main = pty_main ++ end ++ ++ def name ++ 'Waiting for request to power target' ++ end ++ ++ def run(qemu_out, _qemu_in) ++ expect_or_raise(qemu_out, MINIPUSH_POWER_TARGET_REQUEST) ++ ++ # Now is the time to start QEMU with the chainloader binary. QEMU's virtual tty connects to ++ # the MiniPush instance spawned on pty_main, so that the two processes talk to each other. ++ Process.spawn(@qemu_cmd, in: @pty_main, out: @pty_main, err: '/dev/null') ++ end ++end ++ ++# Extend BootTest so that it listens on the output of a MiniPush instance, which is itself connected ++# to a QEMU instance instead of a real HW. ++class ChainbootTest < BootTest ++ MINIPUSH = '../common/serial/minipush.rb' ++ ++ def initialize(qemu_cmd, payload_path) ++ super(qemu_cmd, EXPECTED_PRINT) ++ ++ @test_name = 'Boot test using Minipush' ++ ++ @payload_path = payload_path ++ end ++ ++ private ++ ++ # override ++ def setup ++ pty_main, pty_secondary = PTY.open ++ mp_out, _mp_in = PTY.spawn("ruby #{MINIPUSH} #{pty_secondary.path} #{@payload_path}") ++ ++ # The subtests (from this class and the parents) listen on @qemu_out_wrapped. Hence, point ++ # it to MiniPush's output. ++ @qemu_out_wrapped = PTYLoggerWrapper.new(mp_out, "\r\n") ++ ++ # Important: Run this subtest before the one in the parent class. ++ @console_subtests.prepend(PowerTargetRequestTest.new(@qemu_cmd, pty_main)) ++ end ++ ++ # override ++ def finish ++ super() ++ @test_output.map! { |x| x.gsub(/.*\r/, ' ') } ++ end ++end ++ ++##-------------------------------------------------------------------------------------------------- ++## Execution starts here ++##-------------------------------------------------------------------------------------------------- ++payload_path = ARGV.pop ++qemu_cmd = ARGV.join(' ') ++ ++ChainbootTest.new(qemu_cmd, payload_path).run + +diff -uNr 05_drivers_gpio_uart/update.sh 06_uart_chainloader/update.sh +--- 05_drivers_gpio_uart/update.sh ++++ 06_uart_chainloader/update.sh +@@ -0,0 +1,8 @@ ++#!/usr/bin/env bash ++ ++cd ../05_drivers_gpio_uart ++BSP=rpi4 make ++cp kernel8.img ../06_uart_chainloader/demo_payload_rpi4.img ++make ++cp kernel8.img ../06_uart_chainloader/demo_payload_rpi3.img ++rm kernel8.img + +``` diff --git a/06_uart_chainloader/build.rs b/06_uart_chainloader/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/06_uart_chainloader/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/06_uart_chainloader/demo_payload_rpi3.img b/06_uart_chainloader/demo_payload_rpi3.img new file mode 100755 index 000000000..8109de38e Binary files /dev/null and b/06_uart_chainloader/demo_payload_rpi3.img differ diff --git a/06_uart_chainloader/demo_payload_rpi4.img b/06_uart_chainloader/demo_payload_rpi4.img new file mode 100755 index 000000000..807da95b3 Binary files /dev/null and b/06_uart_chainloader/demo_payload_rpi4.img differ diff --git a/06_uart_chainloader/src/_arch/aarch64/cpu.rs b/06_uart_chainloader/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..f1f1e9aff --- /dev/null +++ b/06_uart_chainloader/src/_arch/aarch64/cpu.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Spin for `n` cycles. +#[cfg(feature = "bsp_rpi3")] +#[inline(always)] +pub fn spin_for_cycles(n: usize) { + for _ in 0..n { + asm::nop(); + } +} + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff --git a/06_uart_chainloader/src/_arch/aarch64/cpu/boot.rs b/06_uart_chainloader/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..2a6c46492 --- /dev/null +++ b/06_uart_chainloader/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff --git a/06_uart_chainloader/src/_arch/aarch64/cpu/boot.s b/06_uart_chainloader/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..3ed0d4941 --- /dev/null +++ b/06_uart_chainloader/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +// Load the address of a symbol into a register, absolute. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_ABS register, symbol + movz \register, #:abs_g2:\symbol + movk \register, #:abs_g1_nc:\symbol + movk \register, #:abs_g0_nc:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed on the boot core. Park it otherwise. + mrs x0, MPIDR_EL1 + and x0, x0, {CONST_CORE_ID_MASK} + ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x0, x1 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_ABS x0, __bss_start + ADR_ABS x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_relocate_binary + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Next, relocate the binary. +.L_relocate_binary: + ADR_REL x0, __binary_nonzero_start // The address the binary got loaded to. + ADR_ABS x1, __binary_nonzero_start // The address the binary was linked to. + ADR_ABS x2, __binary_nonzero_end_exclusive + +.L_copy_loop: + ldr x3, [x0], #8 + str x3, [x1], #8 + cmp x1, x2 + b.lo .L_copy_loop + + // Prepare the jump to Rust code. + // Set the stack pointer. + ADR_ABS x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Jump to the relocated Rust code. + ADR_ABS x1, _start_rust + br x1 + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/06_uart_chainloader/src/bsp.rs b/06_uart_chainloader/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/06_uart_chainloader/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/06_uart_chainloader/src/bsp/device_driver.rs b/06_uart_chainloader/src/bsp/device_driver.rs new file mode 100644 index 000000000..64049a4cf --- /dev/null +++ b/06_uart_chainloader/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/06_uart_chainloader/src/bsp/device_driver/bcm.rs b/06_uart_chainloader/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..1c343d1d7 --- /dev/null +++ b/06_uart_chainloader/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..920b4c00c --- /dev/null +++ b/06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::cpu; + + // Make an educated guess for a good delay value (Sequence described in the BCM2837 + // peripherals PDF). + // + // - According to Wikipedia, the fastest RPi4 clocks around 1.5 GHz. + // - The Linux 2837 GPIO driver waits 1 µs between the steps. + // + // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs + // would the CPU be clocked at 2 GHz. + const DELAY: usize = 2000; + + self.registers.GPPUD.write(GPPUD::PUD::Off); + cpu::spin_for_cycles(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + cpu::spin_for_cycles(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..50a069ea1 --- /dev/null +++ b/06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,402 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let ret = self.registers.DR.get() as u8 as char; + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff --git a/06_uart_chainloader/src/bsp/device_driver/common.rs b/06_uart_chainloader/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..dfe7d8ef3 --- /dev/null +++ b/06_uart_chainloader/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff --git a/06_uart_chainloader/src/bsp/raspberrypi.rs b/06_uart_chainloader/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..3ea864dc7 --- /dev/null +++ b/06_uart_chainloader/src/bsp/raspberrypi.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/06_uart_chainloader/src/bsp/raspberrypi/cpu.rs b/06_uart_chainloader/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/06_uart_chainloader/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/06_uart_chainloader/src/bsp/raspberrypi/driver.rs b/06_uart_chainloader/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..2a80ee2c5 --- /dev/null +++ b/06_uart_chainloader/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} diff --git a/06_uart_chainloader/src/bsp/raspberrypi/kernel.ld b/06_uart_chainloader/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..c84b62381 --- /dev/null +++ b/06_uart_chainloader/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,83 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + /* Set the link address to 32 MiB */ + . = 0x2000000; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __binary_nonzero_start = .; + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ + . = ALIGN(8); + __binary_nonzero_end_exclusive = .; + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/06_uart_chainloader/src/bsp/raspberrypi/memory.rs b/06_uart_chainloader/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..ee72b27a0 --- /dev/null +++ b/06_uart_chainloader/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The address on which the Raspberry firmware loads every binary by default. +#[inline(always)] +pub fn board_default_load_addr() -> *const u64 { + map::BOARD_DEFAULT_LOAD_ADDRESS as _ +} diff --git a/06_uart_chainloader/src/console.rs b/06_uart_chainloader/src/console.rs new file mode 100644 index 000000000..a83f86fe0 --- /dev/null +++ b/06_uart_chainloader/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization::{self, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) +} diff --git a/06_uart_chainloader/src/console/null_console.rs b/06_uart_chainloader/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/06_uart_chainloader/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/06_uart_chainloader/src/cpu.rs b/06_uart_chainloader/src/cpu.rs new file mode 100644 index 000000000..eacb8924a --- /dev/null +++ b/06_uart_chainloader/src/cpu.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "bsp_rpi3")] +pub use arch_cpu::spin_for_cycles; diff --git a/06_uart_chainloader/src/cpu/boot.rs b/06_uart_chainloader/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/06_uart_chainloader/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/06_uart_chainloader/src/driver.rs b/06_uart_chainloader/src/driver.rs new file mode 100644 index 000000000..53592c66b --- /dev/null +++ b/06_uart_chainloader/src/driver.rs @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::synchronization::{interface::Mutex, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } +} diff --git a/06_uart_chainloader/src/main.rs b/06_uart_chainloader/src/main.rs new file mode 100644 index 000000000..dd82ec3fd --- /dev/null +++ b/06_uart_chainloader/src/main.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![feature(asm_const)] +#![feature(format_args_nl)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![no_main] +#![no_std] + +mod bsp; +mod console; +mod cpu; +mod driver; +mod panic_wait; +mod print; +mod synchronization; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order. +unsafe fn kernel_init() -> ! { + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. + + // Transition from unsafe to safe. + kernel_main() +} + +const MINILOAD_LOGO: &str = r#" + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| +"#; + +/// The main function running after the early init. +fn kernel_main() -> ! { + use console::console; + + println!("{}", MINILOAD_LOGO); + println!("{:^37}", bsp::board_name()); + println!(); + println!("[ML] Requesting binary"); + console().flush(); + + // Discard any spurious received characters before starting with the loader protocol. + console().clear_rx(); + + // Notify `Minipush` to send the binary. + for _ in 0..3 { + console().write_char(3 as char); + } + + // Read the binary's size. + let mut size: u32 = u32::from(console().read_char() as u8); + size |= u32::from(console().read_char() as u8) << 8; + size |= u32::from(console().read_char() as u8) << 16; + size |= u32::from(console().read_char() as u8) << 24; + + // Trust it's not too big. + console().write_char('O'); + console().write_char('K'); + + let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; + unsafe { + // Read the kernel byte by byte. + for i in 0..size { + core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) + } + } + + println!("[ML] Loaded! Executing the payload now\n"); + console().flush(); + + // Use black magic to create a function pointer. + let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; + + // Jump to loaded kernel! + kernel() +} diff --git a/06_uart_chainloader/src/panic_wait.rs b/06_uart_chainloader/src/panic_wait.rs new file mode 100644 index 000000000..5bb0896e4 --- /dev/null +++ b/06_uart_chainloader/src/panic_wait.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + cpu::wait_forever() +} diff --git a/06_uart_chainloader/src/print.rs b/06_uart_chainloader/src/print.rs new file mode 100644 index 000000000..6de99572d --- /dev/null +++ b/06_uart_chainloader/src/print.rs @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} diff --git a/06_uart_chainloader/src/synchronization.rs b/06_uart_chainloader/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/06_uart_chainloader/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/06_uart_chainloader/tests/chainboot_test.rb b/06_uart_chainloader/tests/chainboot_test.rb new file mode 100644 index 000000000..00de42a36 --- /dev/null +++ b/06_uart_chainloader/tests/chainboot_test.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2020-2023 Andre Richter + +require_relative '../../common/serial/minipush' +require_relative '../../common/tests/boot_test' +require 'pty' + +# Match for the last print that 'demo_payload_rpiX.img' produces. +EXPECTED_PRINT = 'Echoing input now' + +# Wait for request to power the target. +class PowerTargetRequestTest < SubtestBase + MINIPUSH_POWER_TARGET_REQUEST = 'Please power the target now' + + def initialize(qemu_cmd, pty_main) + super() + @qemu_cmd = qemu_cmd + @pty_main = pty_main + end + + def name + 'Waiting for request to power target' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, MINIPUSH_POWER_TARGET_REQUEST) + + # Now is the time to start QEMU with the chainloader binary. QEMU's virtual tty connects to + # the MiniPush instance spawned on pty_main, so that the two processes talk to each other. + Process.spawn(@qemu_cmd, in: @pty_main, out: @pty_main, err: '/dev/null') + end +end + +# Extend BootTest so that it listens on the output of a MiniPush instance, which is itself connected +# to a QEMU instance instead of a real HW. +class ChainbootTest < BootTest + MINIPUSH = '../common/serial/minipush.rb' + + def initialize(qemu_cmd, payload_path) + super(qemu_cmd, EXPECTED_PRINT) + + @test_name = 'Boot test using Minipush' + + @payload_path = payload_path + end + + private + + # override + def setup + pty_main, pty_secondary = PTY.open + mp_out, _mp_in = PTY.spawn("ruby #{MINIPUSH} #{pty_secondary.path} #{@payload_path}") + + # The subtests (from this class and the parents) listen on @qemu_out_wrapped. Hence, point + # it to MiniPush's output. + @qemu_out_wrapped = PTYLoggerWrapper.new(mp_out, "\r\n") + + # Important: Run this subtest before the one in the parent class. + @console_subtests.prepend(PowerTargetRequestTest.new(@qemu_cmd, pty_main)) + end + + # override + def finish + super() + @test_output.map! { |x| x.gsub(/.*\r/, ' ') } + end +end + +## ------------------------------------------------------------------------------------------------- +## Execution starts here +## ------------------------------------------------------------------------------------------------- +payload_path = ARGV.pop +qemu_cmd = ARGV.join(' ') + +ChainbootTest.new(qemu_cmd, payload_path).run diff --git a/06_uart_chainloader/update.sh b/06_uart_chainloader/update.sh new file mode 100755 index 000000000..5fac48ba0 --- /dev/null +++ b/06_uart_chainloader/update.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +cd ../05_drivers_gpio_uart +BSP=rpi4 make +cp kernel8.img ../06_uart_chainloader/demo_payload_rpi4.img +make +cp kernel8.img ../06_uart_chainloader/demo_payload_rpi3.img +rm kernel8.img diff --git a/07_timestamps/.vscode/settings.json b/07_timestamps/.vscode/settings.json new file mode 100644 index 000000000..bfa278e9a --- /dev/null +++ b/07_timestamps/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/07_timestamps/Cargo.lock b/07_timestamps/Cargo.lock new file mode 100644 index 000000000..be8e7c137 --- /dev/null +++ b/07_timestamps/Cargo.lock @@ -0,0 +1,26 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.7.0" +dependencies = [ + "aarch64-cpu", + "tock-registers", +] + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/07_timestamps/Cargo.toml b/07_timestamps/Cargo.toml new file mode 100644 index 000000000..f4e4bcf69 --- /dev/null +++ b/07_timestamps/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "mingo" +version = "0.7.0" +authors = ["Andre Richter "] +edition = "2021" + +[profile.release] +lto = true + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] + +[[bin]] +name = "kernel" +path = "src/main.rs" + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/07_timestamps/Makefile b/07_timestamps/Makefile new file mode 100644 index 000000000..b13f0dfb7 --- /dev/null +++ b/07_timestamps/Makefile @@ -0,0 +1,239 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DEV = --privileged -v /dev:/dev + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/07_timestamps/README.CN.md b/07_timestamps/README.CN.md new file mode 100644 index 000000000..1192996d3 --- /dev/null +++ b/07_timestamps/README.CN.md @@ -0,0 +1,45 @@ +# 教程 07 - 时间戳 + +## tl;dr + +- 我们为计时器硬件添加了抽象,并在`_arch/aarch64`中实现了ARM架构计时器。 +- 新的计时器函数用于给UART打印添加时间戳,并且用于消除`GPIO`设备驱动中基于周期的延迟,从而提高准确性。 +- 添加了`warn!()`宏。 + +## 测试它 + +请通过 chainboot 进行检查(在上一个教程中添加)。 +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 12 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.143123] mingo version 0.7.0 +[ 0.143323] Booting on: Raspberry Pi 3 +[ 0.143778] Architectural timer resolution: 52 ns +[ 0.144352] Drivers loaded: +[ 0.144688] 1. BCM PL011 UART +[ 0.145110] 2. BCM GPIO +[W 0.145469] Spin duration smaller than architecturally supported, skipping +[ 0.146313] Spinning for 1 second +[ 1.146715] Spinning for 1 second +[ 2.146938] Spinning for 1 second +``` + +## 相比之前的变化(diff) +请检查[英文版本](README.md#diff-to-previous),这是最新的。 diff --git a/07_timestamps/README.md b/07_timestamps/README.md new file mode 100644 index 000000000..af44e8cc2 --- /dev/null +++ b/07_timestamps/README.md @@ -0,0 +1,985 @@ +# Tutorial 07 - Timestamps + +## tl;dr + +- We add abstractions for timer hardware, and implement them for the ARM architectural timer in + `_arch/aarch64`. +- The new timer functions are used to annotate UART prints with timestamps, and to get rid of the + cycle-based delays in the `GPIO` device driver, which boosts accuracy. +- A `warn!()` macro is added. + +## Test it + +Check it out via chainboot (added in previous tutorial): +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 12 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.143123] mingo version 0.7.0 +[ 0.143323] Booting on: Raspberry Pi 3 +[ 0.143778] Architectural timer resolution: 52 ns +[ 0.144352] Drivers loaded: +[ 0.144688] 1. BCM PL011 UART +[ 0.145110] 2. BCM GPIO +[W 0.145469] Spin duration smaller than architecturally supported, skipping +[ 0.146313] Spinning for 1 second +[ 1.146715] Spinning for 1 second +[ 2.146938] Spinning for 1 second +``` + +## Diff to previous +```diff + +diff -uNr 06_uart_chainloader/Cargo.toml 07_timestamps/Cargo.toml +--- 06_uart_chainloader/Cargo.toml ++++ 07_timestamps/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.6.0" ++version = "0.7.0" + authors = ["Andre Richter "] + edition = "2021" + +Binary files 06_uart_chainloader/demo_payload_rpi3.img and 07_timestamps/demo_payload_rpi3.img differ +Binary files 06_uart_chainloader/demo_payload_rpi4.img and 07_timestamps/demo_payload_rpi4.img differ + +diff -uNr 06_uart_chainloader/Makefile 07_timestamps/Makefile +--- 06_uart_chainloader/Makefile ++++ 07_timestamps/Makefile +@@ -24,29 +24,27 @@ + QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + + ifeq ($(BSP),rpi3) +- TARGET = aarch64-unknown-none-softfloat +- KERNEL_BIN = kernel8.img +- QEMU_BINARY = qemu-system-aarch64 +- QEMU_MACHINE_TYPE = raspi3 +- QEMU_RELEASE_ARGS = -serial stdio -display none +- OBJDUMP_BINARY = aarch64-none-elf-objdump +- NM_BINARY = aarch64-none-elf-nm +- READELF_BINARY = aarch64-none-elf-readelf +- LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi +- RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +- CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img ++ TARGET = aarch64-unknown-none-softfloat ++ KERNEL_BIN = kernel8.img ++ QEMU_BINARY = qemu-system-aarch64 ++ QEMU_MACHINE_TYPE = raspi3 ++ QEMU_RELEASE_ARGS = -serial stdio -display none ++ OBJDUMP_BINARY = aarch64-none-elf-objdump ++ NM_BINARY = aarch64-none-elf-nm ++ READELF_BINARY = aarch64-none-elf-readelf ++ LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi ++ RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 + else ifeq ($(BSP),rpi4) +- TARGET = aarch64-unknown-none-softfloat +- KERNEL_BIN = kernel8.img +- QEMU_BINARY = qemu-system-aarch64 +- QEMU_MACHINE_TYPE = +- QEMU_RELEASE_ARGS = -serial stdio -display none +- OBJDUMP_BINARY = aarch64-none-elf-objdump +- NM_BINARY = aarch64-none-elf-nm +- READELF_BINARY = aarch64-none-elf-readelf +- LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi +- RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +- CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img ++ TARGET = aarch64-unknown-none-softfloat ++ KERNEL_BIN = kernel8.img ++ QEMU_BINARY = qemu-system-aarch64 ++ QEMU_MACHINE_TYPE = ++ QEMU_RELEASE_ARGS = -serial stdio -display none ++ OBJDUMP_BINARY = aarch64-none-elf-objdump ++ NM_BINARY = aarch64-none-elf-nm ++ READELF_BINARY = aarch64-none-elf-readelf ++ LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi ++ RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 + endif + + # Export for build.rs. +@@ -92,7 +90,7 @@ + -O binary + + EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +-EXEC_TEST_MINIPUSH = ruby tests/chainboot_test.rb ++EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb + EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + + ##------------------------------------------------------------------------------ +@@ -162,7 +160,7 @@ + ##------------------------------------------------------------------------------ + ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +-qemu qemuasm: ++qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + + else # QEMU is supported. +@@ -171,17 +169,13 @@ + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +-qemuasm: $(KERNEL_BIN) +- $(call color_header, "Launching QEMU with ASM output") +- @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm +- + endif + + ##------------------------------------------------------------------------------ + ## Push the kernel to the real HW target + ##------------------------------------------------------------------------------ + chainboot: $(KERNEL_BIN) +- @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) ++ @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + + ##------------------------------------------------------------------------------ + ## Run clippy +@@ -238,8 +232,7 @@ + ##------------------------------------------------------------------------------ + test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") +- @$(DOCKER_TEST) $(EXEC_TEST_MINIPUSH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) \ +- -kernel $(KERNEL_BIN) $(CHAINBOOT_DEMO_PAYLOAD) ++ @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + + test: test_boot + + +diff -uNr 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s 07_timestamps/src/_arch/aarch64/cpu/boot.s +--- 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s ++++ 07_timestamps/src/_arch/aarch64/cpu/boot.s +@@ -18,17 +18,6 @@ + add \register, \register, #:lo12:\symbol + .endm + +-// Load the address of a symbol into a register, absolute. +-// +-// # Resources +-// +-// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +-.macro ADR_ABS register, symbol +- movz \register, #:abs_g2:\symbol +- movk \register, #:abs_g1_nc:\symbol +- movk \register, #:abs_g0_nc:\symbol +-.endm +- + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -48,35 +37,31 @@ + // If execution reaches here, it is the boot core. + + // Initialize DRAM. +- ADR_ABS x0, __bss_start +- ADR_ABS x1, __bss_end_exclusive ++ ADR_REL x0, __bss_start ++ ADR_REL x1, __bss_end_exclusive + + .L_bss_init_loop: + cmp x0, x1 +- b.eq .L_relocate_binary ++ b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + +- // Next, relocate the binary. +-.L_relocate_binary: +- ADR_REL x0, __binary_nonzero_start // The address the binary got loaded to. +- ADR_ABS x1, __binary_nonzero_start // The address the binary was linked to. +- ADR_ABS x2, __binary_nonzero_end_exclusive +- +-.L_copy_loop: +- ldr x3, [x0], #8 +- str x3, [x1], #8 +- cmp x1, x2 +- b.lo .L_copy_loop +- + // Prepare the jump to Rust code. ++.L_prepare_rust: + // Set the stack pointer. +- ADR_ABS x0, __boot_core_stack_end_exclusive ++ ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + +- // Jump to the relocated Rust code. +- ADR_ABS x1, _start_rust +- br x1 ++ // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. ++ // Abort if the frequency read back as 0. ++ ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs ++ mrs x2, CNTFRQ_EL0 ++ cmp x2, xzr ++ b.eq .L_parking_loop ++ str w2, [x1] ++ ++ // Jump to Rust code. ++ b _start_rust + + // Infinitely wait for events (aka "park the core"). + .L_parking_loop: + +diff -uNr 06_uart_chainloader/src/_arch/aarch64/cpu.rs 07_timestamps/src/_arch/aarch64/cpu.rs +--- 06_uart_chainloader/src/_arch/aarch64/cpu.rs ++++ 07_timestamps/src/_arch/aarch64/cpu.rs +@@ -19,15 +19,6 @@ + + pub use asm::nop; + +-/// Spin for `n` cycles. +-#[cfg(feature = "bsp_rpi3")] +-#[inline(always)] +-pub fn spin_for_cycles(n: usize) { +- for _ in 0..n { +- asm::nop(); +- } +-} +- + /// Pause execution on the core. + #[inline(always)] + pub fn wait_forever() -> ! { + +diff -uNr 06_uart_chainloader/src/_arch/aarch64/time.rs 07_timestamps/src/_arch/aarch64/time.rs +--- 06_uart_chainloader/src/_arch/aarch64/time.rs ++++ 07_timestamps/src/_arch/aarch64/time.rs +@@ -0,0 +1,162 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Architectural timer primitives. ++//! ++//! # Orientation ++//! ++//! Since arch modules are imported into generic modules using the path attribute, the path of this ++//! file is: ++//! ++//! crate::time::arch_time ++ ++use crate::warn; ++use aarch64_cpu::{asm::barrier, registers::*}; ++use core::{ ++ num::{NonZeroU128, NonZeroU32, NonZeroU64}, ++ ops::{Add, Div}, ++ time::Duration, ++}; ++use tock_registers::interfaces::Readable; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); ++ ++#[derive(Copy, Clone, PartialOrd, PartialEq)] ++struct GenericTimerCounterValue(u64); ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is ++/// executed. This given value here is just a (safe) dummy. ++#[no_mangle] ++static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++fn arch_timer_counter_frequency() -> NonZeroU32 { ++ // Read volatile is needed here to prevent the compiler from optimizing ++ // ARCH_TIMER_COUNTER_FREQUENCY away. ++ // ++ // This is safe, because all the safety requirements as stated in read_volatile()'s ++ // documentation are fulfilled. ++ unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } ++} ++ ++impl GenericTimerCounterValue { ++ pub const MAX: Self = GenericTimerCounterValue(u64::MAX); ++} ++ ++impl Add for GenericTimerCounterValue { ++ type Output = Self; ++ ++ fn add(self, other: Self) -> Self { ++ GenericTimerCounterValue(self.0.wrapping_add(other.0)) ++ } ++} ++ ++impl From for Duration { ++ fn from(counter_value: GenericTimerCounterValue) -> Self { ++ if counter_value.0 == 0 { ++ return Duration::ZERO; ++ } ++ ++ let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); ++ ++ // Div implementation for u64 cannot panic. ++ let secs = counter_value.0.div(frequency); ++ ++ // This is safe, because frequency can never be greater than u32::MAX, which means the ++ // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, ++ // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. ++ // ++ // The subsequent division ensures the result fits into u32, since the max result is smaller ++ // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. ++ let sub_second_counter_value = counter_value.0 modulo frequency; ++ let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } ++ .div(frequency) as u32; ++ ++ Duration::new(secs, nanos) ++ } ++} ++ ++fn max_duration() -> Duration { ++ Duration::from(GenericTimerCounterValue::MAX) ++} ++ ++impl TryFrom for GenericTimerCounterValue { ++ type Error = &'static str; ++ ++ fn try_from(duration: Duration) -> Result { ++ if duration < resolution() { ++ return Ok(GenericTimerCounterValue(0)); ++ } ++ ++ if duration > max_duration() { ++ return Err("Conversion error. Duration too big"); ++ } ++ ++ let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; ++ let duration: u128 = duration.as_nanos(); ++ ++ // This is safe, because frequency can never be greater than u32::MAX, and ++ // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. ++ let counter_value = ++ unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); ++ ++ // Since we checked above that we are <= max_duration(), just cast to u64. ++ Ok(GenericTimerCounterValue(counter_value as u64)) ++ } ++} ++ ++#[inline(always)] ++fn read_cntpct() -> GenericTimerCounterValue { ++ // Prevent that the counter is read ahead of time due to out-of-order execution. ++ barrier::isb(barrier::SY); ++ let cnt = CNTPCT_EL0.get(); ++ ++ GenericTimerCounterValue(cnt) ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// The timer's resolution. ++pub fn resolution() -> Duration { ++ Duration::from(GenericTimerCounterValue(1)) ++} ++ ++/// The uptime since power-on of the device. ++/// ++/// This includes time consumed by firmware and bootloaders. ++pub fn uptime() -> Duration { ++ read_cntpct().into() ++} ++ ++/// Spin for a given duration. ++pub fn spin_for(duration: Duration) { ++ let curr_counter_value = read_cntpct(); ++ ++ let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { ++ Err(msg) => { ++ warn!("spin_for: {}. Skipping", msg); ++ return; ++ } ++ Ok(val) => val, ++ }; ++ let counter_value_target = curr_counter_value + counter_value_delta; ++ ++ // Busy wait. ++ // ++ // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. ++ while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} ++} + +diff -uNr 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +--- 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ++++ 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +@@ -140,25 +140,19 @@ + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { +- use crate::cpu; ++ use crate::time; ++ use core::time::Duration; + +- // Make an educated guess for a good delay value (Sequence described in the BCM2837 +- // peripherals PDF). +- // +- // - According to Wikipedia, the fastest RPi4 clocks around 1.5 GHz. +- // - The Linux 2837 GPIO driver waits 1 µs between the steps. +- // +- // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs +- // would the CPU be clocked at 2 GHz. +- const DELAY: usize = 2000; ++ // The Linux 2837 GPIO driver waits 1 µs between the steps. ++ const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); +- cpu::spin_for_cycles(DELAY); ++ time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); +- cpu::spin_for_cycles(DELAY); ++ time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + +diff -uNr 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +--- 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ++++ 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +@@ -275,7 +275,7 @@ + } + + /// Retrieve a character. +- fn read_char(&mut self, blocking_mode: BlockingMode) -> Option { ++ fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. +@@ -290,7 +290,12 @@ + } + + // Read one character. +- let ret = self.registers.DR.get() as u8 as char; ++ let mut ret = self.registers.DR.get() as u8 as char; ++ ++ // Convert carrige return to newline. ++ if ret == '\r' { ++ ret = '\n' ++ } + + // Update statistics. + self.chars_read += 1; +@@ -376,14 +381,14 @@ + impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner +- .lock(|inner| inner.read_char(BlockingMode::Blocking).unwrap()) ++ .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner +- .lock(|inner| inner.read_char(BlockingMode::NonBlocking)) ++ .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } + +diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/driver.rs 07_timestamps/src/bsp/raspberrypi/driver.rs +--- 06_uart_chainloader/src/bsp/raspberrypi/driver.rs ++++ 07_timestamps/src/bsp/raspberrypi/driver.rs +@@ -57,6 +57,17 @@ + /// # Safety + /// + /// See child function calls. ++/// ++/// # Note ++/// ++/// Using atomics here relieves us from needing to use `unsafe` for the static variable. ++/// ++/// On `AArch64`, which is the only implemented architecture at the time of writing this, ++/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store ++/// instructions. They are therefore safe to use even with MMU + caching deactivated. ++/// ++/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load ++/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store + pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + +diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld 07_timestamps/src/bsp/raspberrypi/kernel.ld +--- 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld ++++ 07_timestamps/src/bsp/raspberrypi/kernel.ld +@@ -3,6 +3,8 @@ + * Copyright (c) 2018-2023 Andre Richter + */ + ++__rpi_phys_dram_start_addr = 0; ++ + /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ + __rpi_phys_binary_load_addr = 0x80000; + +@@ -26,8 +28,7 @@ + + SECTIONS + { +- /* Set the link address to 32 MiB */ +- . = 0x2000000; ++ . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack +@@ -44,7 +45,6 @@ + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ +- __binary_nonzero_start = .; + .text : + { + KEEP(*(.text._start)) +@@ -60,10 +60,6 @@ + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + +- /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ +- . = ALIGN(8); +- __binary_nonzero_end_exclusive = .; +- + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + +diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/memory.rs 07_timestamps/src/bsp/raspberrypi/memory.rs +--- 06_uart_chainloader/src/bsp/raspberrypi/memory.rs ++++ 07_timestamps/src/bsp/raspberrypi/memory.rs +@@ -11,7 +11,6 @@ + /// The board's physical memory map. + #[rustfmt::skip] + pub(super) mod map { +- pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; +@@ -36,13 +35,3 @@ + pub const PL011_UART_START: usize = START + UART_OFFSET; + } + } +- +-//-------------------------------------------------------------------------------------------------- +-// Public Code +-//-------------------------------------------------------------------------------------------------- +- +-/// The address on which the Raspberry firmware loads every binary by default. +-#[inline(always)] +-pub fn board_default_load_addr() -> *const u64 { +- map::BOARD_DEFAULT_LOAD_ADDRESS as _ +-} + +diff -uNr 06_uart_chainloader/src/cpu.rs 07_timestamps/src/cpu.rs +--- 06_uart_chainloader/src/cpu.rs ++++ 07_timestamps/src/cpu.rs +@@ -14,6 +14,3 @@ + // Architectural Public Reexports + //-------------------------------------------------------------------------------------------------- + pub use arch_cpu::{nop, wait_forever}; +- +-#[cfg(feature = "bsp_rpi3")] +-pub use arch_cpu::spin_for_cycles; + +diff -uNr 06_uart_chainloader/src/driver.rs 07_timestamps/src/driver.rs +--- 06_uart_chainloader/src/driver.rs ++++ 07_timestamps/src/driver.rs +@@ -4,7 +4,10 @@ + + //! Driver support. + +-use crate::synchronization::{interface::Mutex, NullLock}; ++use crate::{ ++ info, ++ synchronization::{interface::Mutex, NullLock}, ++}; + + //-------------------------------------------------------------------------------------------------- + // Private Definitions +@@ -151,4 +154,14 @@ + } + }); + } ++ ++ /// Enumerate all registered device drivers. ++ pub fn enumerate(&self) { ++ let mut i: usize = 1; ++ self.for_each_descriptor(|descriptor| { ++ info!(" {}. {}", i, descriptor.device_driver.compatible()); ++ ++ i += 1; ++ }); ++ } + } + +diff -uNr 06_uart_chainloader/src/main.rs 07_timestamps/src/main.rs +--- 06_uart_chainloader/src/main.rs ++++ 07_timestamps/src/main.rs +@@ -108,9 +108,12 @@ + + #![allow(clippy::upper_case_acronyms)] + #![feature(asm_const)] ++#![feature(const_option)] + #![feature(format_args_nl)] ++#![feature(nonzero_min_max)] + #![feature(panic_info_message)] + #![feature(trait_alias)] ++#![feature(unchecked_math)] + #![no_main] + #![no_std] + +@@ -121,6 +124,7 @@ + mod panic_wait; + mod print; + mod synchronization; ++mod time; + + /// Early init code. + /// +@@ -142,55 +146,30 @@ + kernel_main() + } + +-const MINILOAD_LOGO: &str = r#" +- __ __ _ _ _ _ +-| \/ (_)_ _ (_) | ___ __ _ __| | +-| |\/| | | ' \| | |__/ _ \/ _` / _` | +-|_| |_|_|_||_|_|____\___/\__,_\__,_| +-"#; +- + /// The main function running after the early init. + fn kernel_main() -> ! { +- use console::console; +- +- println!("{}", MINILOAD_LOGO); +- println!("{:^37}", bsp::board_name()); +- println!(); +- println!("[ML] Requesting binary"); +- console().flush(); +- +- // Discard any spurious received characters before starting with the loader protocol. +- console().clear_rx(); +- +- // Notify `Minipush` to send the binary. +- for _ in 0..3 { +- console().write_char(3 as char); +- } ++ use core::time::Duration; + +- // Read the binary's size. +- let mut size: u32 = u32::from(console().read_char() as u8); +- size |= u32::from(console().read_char() as u8) << 8; +- size |= u32::from(console().read_char() as u8) << 16; +- size |= u32::from(console().read_char() as u8) << 24; +- +- // Trust it's not too big. +- console().write_char('O'); +- console().write_char('K'); +- +- let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; +- unsafe { +- // Read the kernel byte by byte. +- for i in 0..size { +- core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) +- } ++ info!( ++ "{} version {}", ++ env!("CARGO_PKG_NAME"), ++ env!("CARGO_PKG_VERSION") ++ ); ++ info!("Booting on: {}", bsp::board_name()); ++ ++ info!( ++ "Architectural timer resolution: {} ns", ++ time::time_manager().resolution().as_nanos() ++ ); ++ ++ info!("Drivers loaded:"); ++ driver::driver_manager().enumerate(); ++ ++ // Test a failing timer case. ++ time::time_manager().spin_for(Duration::from_nanos(1)); ++ ++ loop { ++ info!("Spinning for 1 second"); ++ time::time_manager().spin_for(Duration::from_secs(1)); + } +- +- println!("[ML] Loaded! Executing the payload now\n"); +- console().flush(); +- +- // Use black magic to create a function pointer. +- let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; +- +- // Jump to loaded kernel! +- kernel() + } + +diff -uNr 06_uart_chainloader/src/panic_wait.rs 07_timestamps/src/panic_wait.rs +--- 06_uart_chainloader/src/panic_wait.rs ++++ 07_timestamps/src/panic_wait.rs +@@ -45,15 +45,18 @@ + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + ++ let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( +- "Kernel panic!\n\n\ ++ "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", ++ timestamp.as_secs(), ++ timestamp.subsec_micros(), + location, + line, + column, + +diff -uNr 06_uart_chainloader/src/print.rs 07_timestamps/src/print.rs +--- 06_uart_chainloader/src/print.rs ++++ 07_timestamps/src/print.rs +@@ -34,3 +34,51 @@ + $crate::print::_print(format_args_nl!($($arg)*)); + }) + } ++ ++/// Prints an info, with a newline. ++#[macro_export] ++macro_rules! info { ++ ($string:expr) => ({ ++ let timestamp = $crate::time::time_manager().uptime(); ++ ++ $crate::print::_print(format_args_nl!( ++ concat!("[ {:>3}.{:06}] ", $string), ++ timestamp.as_secs(), ++ timestamp.subsec_micros(), ++ )); ++ }); ++ ($format_string:expr, $($arg:tt)*) => ({ ++ let timestamp = $crate::time::time_manager().uptime(); ++ ++ $crate::print::_print(format_args_nl!( ++ concat!("[ {:>3}.{:06}] ", $format_string), ++ timestamp.as_secs(), ++ timestamp.subsec_micros(), ++ $($arg)* ++ )); ++ }) ++} ++ ++/// Prints a warning, with a newline. ++#[macro_export] ++macro_rules! warn { ++ ($string:expr) => ({ ++ let timestamp = $crate::time::time_manager().uptime(); ++ ++ $crate::print::_print(format_args_nl!( ++ concat!("[W {:>3}.{:06}] ", $string), ++ timestamp.as_secs(), ++ timestamp.subsec_micros(), ++ )); ++ }); ++ ($format_string:expr, $($arg:tt)*) => ({ ++ let timestamp = $crate::time::time_manager().uptime(); ++ ++ $crate::print::_print(format_args_nl!( ++ concat!("[W {:>3}.{:06}] ", $format_string), ++ timestamp.as_secs(), ++ timestamp.subsec_micros(), ++ $($arg)* ++ )); ++ }) ++} + +diff -uNr 06_uart_chainloader/src/time.rs 07_timestamps/src/time.rs +--- 06_uart_chainloader/src/time.rs ++++ 07_timestamps/src/time.rs +@@ -0,0 +1,57 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Timer primitives. ++ ++#[cfg(target_arch = "aarch64")] ++#[path = "_arch/aarch64/time.rs"] ++mod arch_time; ++ ++use core::time::Duration; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Provides time management functions. ++pub struct TimeManager; ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static TIME_MANAGER: TimeManager = TimeManager::new(); ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Return a reference to the global TimeManager. ++pub fn time_manager() -> &'static TimeManager { ++ &TIME_MANAGER ++} ++ ++impl TimeManager { ++ /// Create an instance. ++ pub const fn new() -> Self { ++ Self ++ } ++ ++ /// The timer's resolution. ++ pub fn resolution(&self) -> Duration { ++ arch_time::resolution() ++ } ++ ++ /// The uptime since power-on of the device. ++ /// ++ /// This includes time consumed by firmware and bootloaders. ++ pub fn uptime(&self) -> Duration { ++ arch_time::uptime() ++ } ++ ++ /// Spin for a given duration. ++ pub fn spin_for(&self, duration: Duration) { ++ arch_time::spin_for(duration) ++ } ++} + +diff -uNr 06_uart_chainloader/tests/boot_test_string.rb 07_timestamps/tests/boot_test_string.rb +--- 06_uart_chainloader/tests/boot_test_string.rb ++++ 07_timestamps/tests/boot_test_string.rb +@@ -0,0 +1,3 @@ ++# frozen_string_literal: true ++ ++EXPECTED_PRINT = 'Spinning for 1 second' + +diff -uNr 06_uart_chainloader/tests/chainboot_test.rb 07_timestamps/tests/chainboot_test.rb +--- 06_uart_chainloader/tests/chainboot_test.rb ++++ 07_timestamps/tests/chainboot_test.rb +@@ -1,78 +0,0 @@ +-# frozen_string_literal: true +- +-# SPDX-License-Identifier: MIT OR Apache-2.0 +-# +-# Copyright (c) 2020-2023 Andre Richter +- +-require_relative '../../common/serial/minipush' +-require_relative '../../common/tests/boot_test' +-require 'pty' +- +-# Match for the last print that 'demo_payload_rpiX.img' produces. +-EXPECTED_PRINT = 'Echoing input now' +- +-# Wait for request to power the target. +-class PowerTargetRequestTest < SubtestBase +- MINIPUSH_POWER_TARGET_REQUEST = 'Please power the target now' +- +- def initialize(qemu_cmd, pty_main) +- super() +- @qemu_cmd = qemu_cmd +- @pty_main = pty_main +- end +- +- def name +- 'Waiting for request to power target' +- end +- +- def run(qemu_out, _qemu_in) +- expect_or_raise(qemu_out, MINIPUSH_POWER_TARGET_REQUEST) +- +- # Now is the time to start QEMU with the chainloader binary. QEMU's virtual tty connects to +- # the MiniPush instance spawned on pty_main, so that the two processes talk to each other. +- Process.spawn(@qemu_cmd, in: @pty_main, out: @pty_main, err: '/dev/null') +- end +-end +- +-# Extend BootTest so that it listens on the output of a MiniPush instance, which is itself connected +-# to a QEMU instance instead of a real HW. +-class ChainbootTest < BootTest +- MINIPUSH = '../common/serial/minipush.rb' +- +- def initialize(qemu_cmd, payload_path) +- super(qemu_cmd, EXPECTED_PRINT) +- +- @test_name = 'Boot test using Minipush' +- +- @payload_path = payload_path +- end +- +- private +- +- # override +- def setup +- pty_main, pty_secondary = PTY.open +- mp_out, _mp_in = PTY.spawn("ruby #{MINIPUSH} #{pty_secondary.path} #{@payload_path}") +- +- # The subtests (from this class and the parents) listen on @qemu_out_wrapped. Hence, point +- # it to MiniPush's output. +- @qemu_out_wrapped = PTYLoggerWrapper.new(mp_out, "\r\n") +- +- # Important: Run this subtest before the one in the parent class. +- @console_subtests.prepend(PowerTargetRequestTest.new(@qemu_cmd, pty_main)) +- end +- +- # override +- def finish +- super() +- @test_output.map! { |x| x.gsub(/.*\r/, ' ') } +- end +-end +- +-##-------------------------------------------------------------------------------------------------- +-## Execution starts here +-##-------------------------------------------------------------------------------------------------- +-payload_path = ARGV.pop +-qemu_cmd = ARGV.join(' ') +- +-ChainbootTest.new(qemu_cmd, payload_path).run + +diff -uNr 06_uart_chainloader/update.sh 07_timestamps/update.sh +--- 06_uart_chainloader/update.sh ++++ 07_timestamps/update.sh +@@ -1,8 +0,0 @@ +-#!/usr/bin/env bash +- +-cd ../05_drivers_gpio_uart +-BSP=rpi4 make +-cp kernel8.img ../06_uart_chainloader/demo_payload_rpi4.img +-make +-cp kernel8.img ../06_uart_chainloader/demo_payload_rpi3.img +-rm kernel8.img + +``` diff --git a/07_timestamps/build.rs b/07_timestamps/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/07_timestamps/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/07_timestamps/src/_arch/aarch64/cpu.rs b/07_timestamps/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..602c9789c --- /dev/null +++ b/07_timestamps/src/_arch/aarch64/cpu.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff --git a/07_timestamps/src/_arch/aarch64/cpu/boot.rs b/07_timestamps/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..2a6c46492 --- /dev/null +++ b/07_timestamps/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff --git a/07_timestamps/src/_arch/aarch64/cpu/boot.s b/07_timestamps/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..0b801b4bd --- /dev/null +++ b/07_timestamps/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed on the boot core. Park it otherwise. + mrs x0, MPIDR_EL1 + and x0, x0, {CONST_CORE_ID_MASK} + ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x0, x1 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/07_timestamps/src/_arch/aarch64/time.rs b/07_timestamps/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/07_timestamps/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/07_timestamps/src/bsp.rs b/07_timestamps/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/07_timestamps/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/07_timestamps/src/bsp/device_driver.rs b/07_timestamps/src/bsp/device_driver.rs new file mode 100644 index 000000000..64049a4cf --- /dev/null +++ b/07_timestamps/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/07_timestamps/src/bsp/device_driver/bcm.rs b/07_timestamps/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..1c343d1d7 --- /dev/null +++ b/07_timestamps/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..8e57dfedb --- /dev/null +++ b/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..d92612ea8 --- /dev/null +++ b/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff --git a/07_timestamps/src/bsp/device_driver/common.rs b/07_timestamps/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..dfe7d8ef3 --- /dev/null +++ b/07_timestamps/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff --git a/07_timestamps/src/bsp/raspberrypi.rs b/07_timestamps/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..3ea864dc7 --- /dev/null +++ b/07_timestamps/src/bsp/raspberrypi.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/07_timestamps/src/bsp/raspberrypi/cpu.rs b/07_timestamps/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/07_timestamps/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/07_timestamps/src/bsp/raspberrypi/driver.rs b/07_timestamps/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..7716fe3f7 --- /dev/null +++ b/07_timestamps/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} diff --git a/07_timestamps/src/bsp/raspberrypi/kernel.ld b/07_timestamps/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..f6c188434 --- /dev/null +++ b/07_timestamps/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/07_timestamps/src/bsp/raspberrypi/memory.rs b/07_timestamps/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..cdca14b8a --- /dev/null +++ b/07_timestamps/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } +} diff --git a/07_timestamps/src/console.rs b/07_timestamps/src/console.rs new file mode 100644 index 000000000..a83f86fe0 --- /dev/null +++ b/07_timestamps/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization::{self, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) +} diff --git a/07_timestamps/src/console/null_console.rs b/07_timestamps/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/07_timestamps/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/07_timestamps/src/cpu.rs b/07_timestamps/src/cpu.rs new file mode 100644 index 000000000..67ab79c08 --- /dev/null +++ b/07_timestamps/src/cpu.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; diff --git a/07_timestamps/src/cpu/boot.rs b/07_timestamps/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/07_timestamps/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/07_timestamps/src/driver.rs b/07_timestamps/src/driver.rs new file mode 100644 index 000000000..050e7022f --- /dev/null +++ b/07_timestamps/src/driver.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + info, + synchronization::{interface::Mutex, NullLock}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/07_timestamps/src/main.rs b/07_timestamps/src/main.rs new file mode 100644 index 000000000..b094dacc5 --- /dev/null +++ b/07_timestamps/src/main.rs @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(format_args_nl)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_main] +#![no_std] + +mod bsp; +mod console; +mod cpu; +mod driver; +mod panic_wait; +mod print; +mod synchronization; +mod time; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order. +unsafe fn kernel_init() -> ! { + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + use core::time::Duration; + + info!( + "{} version {}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + info!("Booting on: {}", bsp::board_name()); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + // Test a failing timer case. + time::time_manager().spin_for(Duration::from_nanos(1)); + + loop { + info!("Spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); + } +} diff --git a/07_timestamps/src/panic_wait.rs b/07_timestamps/src/panic_wait.rs new file mode 100644 index 000000000..5776aca87 --- /dev/null +++ b/07_timestamps/src/panic_wait.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + cpu::wait_forever() +} diff --git a/07_timestamps/src/print.rs b/07_timestamps/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/07_timestamps/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/07_timestamps/src/synchronization.rs b/07_timestamps/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/07_timestamps/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/07_timestamps/src/time.rs b/07_timestamps/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/07_timestamps/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/07_timestamps/tests/boot_test_string.rb b/07_timestamps/tests/boot_test_string.rb new file mode 100644 index 000000000..02c3c492a --- /dev/null +++ b/07_timestamps/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Spinning for 1 second' diff --git a/07_uart_chainloader/.vscode/settings.json b/07_uart_chainloader/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/07_uart_chainloader/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/07_uart_chainloader/Cargo.lock b/07_uart_chainloader/Cargo.lock deleted file mode 100644 index 7b2456e16..000000000 --- a/07_uart_chainloader/Cargo.lock +++ /dev/null @@ -1,33 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "register", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/07_uart_chainloader/Cargo.toml b/07_uart_chainloader/Cargo.toml deleted file mode 100644 index b8906da1f..000000000 --- a/07_uart_chainloader/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Optional dependencies -register = { version = "1.x.x", optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/07_uart_chainloader/Makefile b/07_uart_chainloader/Makefile deleted file mode 100644 index 884a29f73..000000000 --- a/07_uart_chainloader/Makefile +++ /dev/null @@ -1,126 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -C relocation-model=pic - CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -C relocation-model=pic - CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DEV = --privileged -v /dev:/dev - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu qemuasm chainboot clippy clean readelf objdump nm \ - check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu qemuasm: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) - -qemuasm: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm -endif - -chainboot: - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ - --section .text \ - --section .got \ - $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/07_uart_chainloader/README.md b/07_uart_chainloader/README.md deleted file mode 100644 index 378b6eb5d..000000000 --- a/07_uart_chainloader/README.md +++ /dev/null @@ -1,586 +0,0 @@ -# Tutorial 07 - UART Chainloader - -## tl;dr - -- Running from an SD card was a nice experience, but it would be extremely tedious to do it for - every new binary. Let's write a [chainloader] using [position independent code]. -- This will be the last binary you need to put on the SD card. Each following tutorial will provide - a `chainboot` target in the `Makefile` that lets you conveniently load the kernel over `UART`. - -[chainloader]: https://en.wikipedia.org/wiki/Chain_loading -[position independent code]: https://en.wikipedia.org/wiki/Position-independent_code - -## Note - -Please note that there is a lot of stuff going on in this tutorial that is very hard to grasp by -only looking at the source code changes. - -Please bear with me until I find the time to write it all down here elaborately. For the time being, -please see this tutorial as an enabler for a convenience feature that allows booting the following -tutorials in a quick manner. - -## Install and test it - -Our chainloader is called `MiniLoad` and is inspired by [raspbootin]. - -You can try it with this tutorial already: -1. Depending on your target hardware:`make` or `BSP=rpi4 make`. -2. Copy `kernel8.img` to the SD card. -3. Execute `make chainboot` or `BSP=rpi4 make chainboot`. -4. Now plug in the USB Serial. -5. Observe the loader fetching a kernel over `UART`: - -> ❗ **NOTE**: By default, `make chainboot` tries to connect to `/dev/ttyUSB0`. -> Should the USB serial on your system have a different name, you have to provide it explicitly. For -> example: -> -> `DEV_SERIAL=/dev/tty.usbserial-0001 make chainboot` - -[raspbootin]: https://github.com/mrvn/raspbootin - -```console -$ make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 3 - -[ML] Requesting binary -[MP] ⏩ Pushing 7 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 -[ML] Loaded! Executing the payload now - -[0] Booting on: Raspberry Pi 3 -[1] Drivers loaded: - 1. BCM GPIO - 2. BCM PL011 UART -[2] Chars written: 93 -[3] Echoing input now -``` - -In this tutorial, a version of the kernel from the previous tutorial is loaded -for demo purposes. In subsequent tuts, it will be the working directory's -kernel. - -## Test it - -The `Makefile` in this tutorial has an additional target, `qemuasm`, that lets -you nicely observe the jump from the loaded address (`0x80_XXX`) to the -relocated code at (`0x0200_0XXX`): - -```console -$ make qemuasm -[...] -IN: -0x0008098c: b0000008 adrp x8, #0x81000 -0x00080990: b0000000 adrp x0, #0x81000 -0x00080994: 912a8000 add x0, x0, #0xaa0 -0x00080998: f9471908 ldr x8, [x8, #0xe30] -0x0008099c: d63f0100 blr x8 - ----------------- -IN: -0x02000b1c: b0000008 adrp x8, #0x2001000 -0x02000b20: b0000009 adrp x9, #0x2001000 -0x02000b24: f9475d08 ldr x8, [x8, #0xeb8] -0x02000b28: f9476129 ldr x9, [x9, #0xec0] -0x02000b2c: eb08013f cmp x9, x8 -0x02000b30: 540000c2 b.hs #0x2000b48 -[...] -``` - -## Diff to previous -```diff -Binary files 06_drivers_gpio_uart/demo_payload_rpi3.img and 07_uart_chainloader/demo_payload_rpi3.img differ -Binary files 06_drivers_gpio_uart/demo_payload_rpi4.img and 07_uart_chainloader/demo_payload_rpi4.img differ - -diff -uNr 06_drivers_gpio_uart/Makefile 07_uart_chainloader/Makefile ---- 06_drivers_gpio_uart/Makefile -+++ 07_uart_chainloader/Makefile -@@ -21,7 +21,8 @@ - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld -- RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -+ RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -C relocation-model=pic -+ CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img - else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img -@@ -31,7 +32,8 @@ - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld -- RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -+ RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -C relocation-model=pic -+ CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img - endif - - # Export for build.rs -@@ -67,13 +69,14 @@ - ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - -- DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) -+ DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) - endif - - EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) --EXEC_MINITERM = ruby ../utils/miniterm.rb -+EXEC_MINIPUSH = ruby ../utils/minipush.rb - --.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu miniterm clippy clean readelf objdump nm check -+.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu qemuasm chainboot clippy clean readelf objdump nm \ -+ check - - all: $(KERNEL_BIN) - -@@ -87,15 +90,18 @@ - $(DOC_CMD) --document-private-items --open - - ifeq ($(QEMU_MACHINE_TYPE),) --qemu: -+qemu qemuasm: - @echo "This board is not yet supported for QEMU." - else - qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -+ -+qemuasm: $(KERNEL_BIN) -+ @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm - endif - --miniterm: -- @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) -+chainboot: -+ @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) - - clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) -@@ -107,7 +113,10 @@ - readelf --headers $(KERNEL_ELF) - - objdump: $(KERNEL_ELF) -- @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt -+ @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ -+ --section .text \ -+ --section .got \ -+ $(KERNEL_ELF) | rustfilt - - nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -diff -uNr 06_drivers_gpio_uart/src/_arch/aarch64/cpu.rs 07_uart_chainloader/src/_arch/aarch64/cpu.rs ---- 06_drivers_gpio_uart/src/_arch/aarch64/cpu.rs -+++ 07_uart_chainloader/src/_arch/aarch64/cpu.rs -@@ -21,12 +21,12 @@ - #[naked] - #[no_mangle] - pub unsafe fn _start() -> ! { -- use crate::runtime_init; -+ use crate::relocate; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); -- runtime_init::runtime_init() -+ relocate::relocate_self() - } else { - // If not core0, infinitely wait for events. - wait_forever() -@@ -55,3 +55,19 @@ - asm::wfe() - } - } -+ -+/// Branch to a raw integer value. -+/// -+/// # Safety -+/// -+/// - This is highly unsafe. Use with care. -+#[inline(always)] -+pub unsafe fn branch_to_raw_addr(addr: usize) -> ! { -+ asm!( -+ "blr {destination:x}", -+ destination = in(reg) addr, -+ options(nomem, nostack) -+ ); -+ -+ core::intrinsics::unreachable() -+} - -diff -uNr 06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ---- 06_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -+++ 07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -@@ -268,6 +268,15 @@ - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } -+ -+ fn flush(&self) { -+ // Spin until TX FIFO empty is set. -+ self.inner.lock(|inner| { -+ while !inner.registers.FR.matches_all(FR::TXFE::SET) { -+ cpu::nop(); -+ } -+ }); -+ } - } - - impl console::interface::Read for PL011Uart { -@@ -278,18 +287,20 @@ - cpu::nop(); - } - -- // Read one character. -- let mut ret = inner.registers.DR.get() as u8 as char; -- -- // Convert carrige return to newline. -- if ret == '\r' { -- ret = '\n' -- } -- - // Update statistics. - inner.chars_read += 1; - -- ret -+ // Read one character. -+ inner.registers.DR.get() as u8 as char -+ }) -+ } -+ -+ fn clear(&self) { -+ self.inner.lock(|inner| { -+ // Read from the RX FIFO until it is indicating empty. -+ while !inner.registers.FR.matches_all(FR::RXFE::SET) { -+ inner.registers.DR.get(); -+ } - }) - } - } - -diff -uNr 06_drivers_gpio_uart/src/bsp/raspberrypi/link.ld 07_uart_chainloader/src/bsp/raspberrypi/link.ld ---- 06_drivers_gpio_uart/src/bsp/raspberrypi/link.ld -+++ 07_uart_chainloader/src/bsp/raspberrypi/link.ld -@@ -5,12 +5,15 @@ - - SECTIONS - { -- /* Set current address to the value from which the RPi starts execution */ -- . = 0x80000; -+ /* Set the link address to 32 MiB */ -+ . = 0x2000000; - -+ __binary_start = .; - .text : - { -- *(.text._start) *(.text*) -+ *(.text._start) -+ KEEP(*(.text.runtime_init)) -+ *(.text*); - } - - .rodata : -@@ -35,5 +38,16 @@ - __bss_end_inclusive = . - 8; - } - -+ .got : -+ { -+ *(.got*) -+ } -+ -+ /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ -+ . = ALIGN(8); -+ __binary_end_inclusive = . - 8; -+ -+ __runtime_init_reloc = runtime_init; -+ - /DISCARD/ : { *(.comment*) } - } - -diff -uNr 06_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs 07_uart_chainloader/src/bsp/raspberrypi/memory.rs ---- 06_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs -+++ 07_uart_chainloader/src/bsp/raspberrypi/memory.rs -@@ -12,6 +12,9 @@ - - // Symbols from the linker script. - extern "Rust" { -+ static __binary_start: UnsafeCell; -+ static __binary_end_inclusive: UnsafeCell; -+ static __runtime_init_reloc: UnsafeCell; - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; - } -@@ -23,10 +26,12 @@ - /// The board's memory map. - #[rustfmt::skip] - pub(super) mod map { -- pub const BOOT_CORE_STACK_END: usize = 0x8_0000; -+ pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - -- pub const GPIO_OFFSET: usize = 0x0020_0000; -- pub const UART_OFFSET: usize = 0x0020_1000; -+ pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; -+ -+ pub const GPIO_OFFSET: usize = 0x0020_0000; -+ pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] -@@ -59,13 +64,35 @@ - map::BOOT_CORE_STACK_END - } - --/// Return the inclusive range spanning the .bss section. -+/// The address on which the Raspberry firmware loads every binary by default. -+#[inline(always)] -+pub fn board_default_load_addr() -> *const u64 { -+ map::BOARD_DEFAULT_LOAD_ADDRESS as _ -+} -+ -+/// Return the inclusive range spanning the relocated kernel binary. -+/// -+/// # Safety -+/// -+/// - Values are provided by the linker script and must be trusted as-is. -+/// - The linker-provided addresses must be u64 aligned. -+pub fn relocated_binary_range_inclusive() -> RangeInclusive<*mut u64> { -+ unsafe { RangeInclusive::new(__binary_start.get(), __binary_end_inclusive.get()) } -+} -+ -+/// The relocated address of function `runtime_init()`. -+#[inline(always)] -+pub fn relocated_runtime_init_addr() -> *const u64 { -+ unsafe { __runtime_init_reloc.get() as _ } -+} -+ -+/// Return the inclusive range spanning the relocated .bss section. - /// - /// # Safety - /// - /// - Values are provided by the linker script and must be trusted as-is. - /// - The linker-provided addresses must be u64 aligned. --pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { -+pub fn relocated_bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - -diff -uNr 06_drivers_gpio_uart/src/console.rs 07_uart_chainloader/src/console.rs ---- 06_drivers_gpio_uart/src/console.rs -+++ 07_uart_chainloader/src/console.rs -@@ -19,6 +19,10 @@ - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; -+ -+ /// Block execution until the last character has been physically put on the TX wire -+ /// (draining TX buffers/FIFOs, if any). -+ fn flush(&self); - } - - /// Console read functions. -@@ -27,6 +31,9 @@ - fn read_char(&self) -> char { - ' ' - } -+ -+ /// Clear RX buffers, if any. -+ fn clear(&self); - } - - /// Console statistics. - -diff -uNr 06_drivers_gpio_uart/src/main.rs 07_uart_chainloader/src/main.rs ---- 06_drivers_gpio_uart/src/main.rs -+++ 07_uart_chainloader/src/main.rs -@@ -100,7 +100,9 @@ - //! - `crate::memory::*` - //! - `crate::bsp::memory::*` - -+#![feature(asm)] - #![feature(const_fn_fn_ptr_basics)] -+#![feature(core_intrinsics)] - #![feature(format_args_nl)] - #![feature(naked_functions)] - #![feature(panic_info_message)] -@@ -109,7 +111,8 @@ - #![no_std] - - // `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls --// `runtime_init()`, which jumps to `kernel_init()`. -+// `relocate::relocate_self()`. `relocate::relocate_self()` calls `runtime_init()`, which jumps to -+// `kernel_init()`. - - mod bsp; - mod console; -@@ -118,6 +121,7 @@ - mod memory; - mod panic_wait; - mod print; -+mod relocate; - mod runtime_init; - mod synchronization; - -@@ -144,35 +148,52 @@ - - /// The main function running after the early init. - fn kernel_main() -> ! { -+ use bsp::console::console; - use console::interface::All; -- use driver::interface::DriverManager; - -- // Wait for user to hit Enter. -- loop { -- if bsp::console::console().read_char() == '\n' { -- break; -+ println!(" __ __ _ _ _ _ "); -+ println!("| \\/ (_)_ _ (_) | ___ __ _ __| |"); -+ println!("| |\\/| | | ' \\| | |__/ _ \\/ _` / _` |"); -+ println!("|_| |_|_|_||_|_|____\\___/\\__,_\\__,_|"); -+ println!(); -+ println!("{:^37}", bsp::board_name()); -+ println!(); -+ println!("[ML] Requesting binary"); -+ console().flush(); -+ -+ // Clear the RX FIFOs, if any, of spurious received characters before starting with the loader -+ // protocol. -+ console().clear(); -+ -+ // Notify `Minipush` to send the binary. -+ for _ in 0..3 { -+ console().write_char(3 as char); -+ } -+ -+ // Read the binary's size. -+ let mut size: u32 = u32::from(console().read_char() as u8); -+ size |= u32::from(console().read_char() as u8) << 8; -+ size |= u32::from(console().read_char() as u8) << 16; -+ size |= u32::from(console().read_char() as u8) << 24; -+ -+ // Trust it's not too big. -+ console().write_char('O'); -+ console().write_char('K'); -+ -+ let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; -+ unsafe { -+ // Read the kernel byte by byte. -+ for i in 0..size { -+ core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) - } - } - -- println!("[0] Booting on: {}", bsp::board_name()); -+ println!("[ML] Loaded! Executing the payload now\n"); -+ console().flush(); - -- println!("[1] Drivers loaded:"); -- for (i, driver) in bsp::driver::driver_manager() -- .all_device_drivers() -- .iter() -- .enumerate() -- { -- println!(" {}. {}", i + 1, driver.compatible()); -- } -+ // Use black magic to get a function pointer. -+ let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; - -- println!( -- "[2] Chars written: {}", -- bsp::console::console().chars_written() -- ); -- println!("[3] Echoing input now"); -- -- loop { -- let c = bsp::console::console().read_char(); -- bsp::console::console().write_char(c); -- } -+ // Jump to loaded kernel! -+ kernel() - } - -diff -uNr 06_drivers_gpio_uart/src/relocate.rs 07_uart_chainloader/src/relocate.rs ---- 06_drivers_gpio_uart/src/relocate.rs -+++ 07_uart_chainloader/src/relocate.rs -@@ -0,0 +1,51 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Relocation code. -+ -+use crate::{bsp, cpu}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Relocates the own binary from `bsp::memory::board_default_load_addr()` to the `__binary_start` -+/// address from the linker script. -+/// -+/// # Safety -+/// -+/// - Only a single core must be active and running this function. -+/// - Function must not use the `bss` section. -+#[inline(never)] -+pub unsafe fn relocate_self() -> ! { -+ let range = bsp::memory::relocated_binary_range_inclusive(); -+ let mut relocated_binary_start_addr = *range.start(); -+ let relocated_binary_end_addr_inclusive = *range.end(); -+ -+ // The address of where the previous firmware loaded us. -+ let mut current_binary_start_addr = bsp::memory::board_default_load_addr(); -+ -+ // Copy the whole binary. -+ while relocated_binary_start_addr <= relocated_binary_end_addr_inclusive { -+ core::ptr::write_volatile( -+ relocated_binary_start_addr, -+ core::ptr::read_volatile(current_binary_start_addr), -+ ); -+ relocated_binary_start_addr = relocated_binary_start_addr.offset(1); -+ current_binary_start_addr = current_binary_start_addr.offset(1); -+ } -+ -+ // The following function calls form a hack to achieve an "absolute jump" to -+ // `runtime_init::runtime_init()` by forcing an indirection through the global offset table -+ // (GOT), so that execution continues from the relocated binary. -+ // -+ // Without this, the address of `runtime_init()` would be calculated as a relative offset from -+ // the current program counter, since we are compiling as `position independent code`. This -+ // would cause us to keep executing from the address to which the firmware loaded us, instead of -+ // the relocated position. -+ // -+ // There likely is a more elegant way to do this. -+ let relocated_runtime_init_addr = bsp::memory::relocated_runtime_init_addr() as usize; -+ cpu::branch_to_raw_addr(relocated_runtime_init_addr) -+} - -diff -uNr 06_drivers_gpio_uart/src/runtime_init.rs 07_uart_chainloader/src/runtime_init.rs ---- 06_drivers_gpio_uart/src/runtime_init.rs -+++ 07_uart_chainloader/src/runtime_init.rs -@@ -17,7 +17,7 @@ - /// - Must only be called pre `kernel_init()`. - #[inline(always)] - unsafe fn zero_bss() { -- memory::zero_volatile(bsp::memory::bss_range_inclusive()); -+ memory::zero_volatile(bsp::memory::relocated_bss_range_inclusive()); - } - - //-------------------------------------------------------------------------------------------------- -@@ -30,6 +30,7 @@ - /// # Safety - /// - /// - Only a single core must be active and running this function. -+#[no_mangle] - pub unsafe fn runtime_init() -> ! { - zero_bss(); - -``` diff --git a/07_uart_chainloader/build.rs b/07_uart_chainloader/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/07_uart_chainloader/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/07_uart_chainloader/demo_payload_rpi3.img b/07_uart_chainloader/demo_payload_rpi3.img deleted file mode 100755 index 9adf8152f..000000000 Binary files a/07_uart_chainloader/demo_payload_rpi3.img and /dev/null differ diff --git a/07_uart_chainloader/demo_payload_rpi4.img b/07_uart_chainloader/demo_payload_rpi4.img deleted file mode 100755 index c3b1ede6c..000000000 Binary files a/07_uart_chainloader/demo_payload_rpi4.img and /dev/null differ diff --git a/07_uart_chainloader/src/_arch/aarch64/cpu.rs b/07_uart_chainloader/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 3121e75ee..000000000 --- a/07_uart_chainloader/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,73 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - use crate::relocate; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); - relocate::relocate_self() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Spin for `n` cycles. -#[cfg(feature = "bsp_rpi3")] -#[inline(always)] -pub fn spin_for_cycles(n: usize) { - for _ in 0..n { - asm::nop(); - } -} - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} - -/// Branch to a raw integer value. -/// -/// # Safety -/// -/// - This is highly unsafe. Use with care. -#[inline(always)] -pub unsafe fn branch_to_raw_addr(addr: usize) -> ! { - asm!( - "blr {destination:x}", - destination = in(reg) addr, - options(nomem, nostack) - ); - - core::intrinsics::unreachable() -} diff --git a/07_uart_chainloader/src/_arch/aarch64/cpu/smp.rs b/07_uart_chainloader/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/07_uart_chainloader/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/07_uart_chainloader/src/bsp.rs b/07_uart_chainloader/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/07_uart_chainloader/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/07_uart_chainloader/src/bsp/device_driver.rs b/07_uart_chainloader/src/bsp/device_driver.rs deleted file mode 100644 index ce7396f22..000000000 --- a/07_uart_chainloader/src/bsp/device_driver.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/07_uart_chainloader/src/bsp/device_driver/bcm.rs b/07_uart_chainloader/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 59071d5d8..000000000 --- a/07_uart_chainloader/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index f5abbee8a..000000000 --- a/07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,221 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::cpu; - - // Make an educated guess for a good delay value (Sequence described in the BCM2837 - // peripherals PDF). - // - // - According to Wikipedia, the fastest Pi3 clocks around 1.4 GHz. - // - The Linux 2837 GPIO driver waits 1 µs between the steps. - // - // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs - // would the CPU be clocked at 2 GHz. - const DELAY: usize = 2000; - - self.registers.GPPUD.write(GPPUD::PUD::Off); - cpu::spin_for_cycles(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - cpu::spin_for_cycles(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index a17d63ee7..000000000 --- a/07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,316 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => _reserved3), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Update statistics. - inner.chars_read += 1; - - // Read one character. - inner.registers.DR.get() as u8 as char - }) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} diff --git a/07_uart_chainloader/src/bsp/device_driver/common.rs b/07_uart_chainloader/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/07_uart_chainloader/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/07_uart_chainloader/src/bsp/raspberrypi.rs b/07_uart_chainloader/src/bsp/raspberrypi.rs deleted file mode 100644 index 10888d37f..000000000 --- a/07_uart_chainloader/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/07_uart_chainloader/src/bsp/raspberrypi/console.rs b/07_uart_chainloader/src/bsp/raspberrypi/console.rs deleted file mode 100644 index d1b60dd82..000000000 --- a/07_uart_chainloader/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} diff --git a/07_uart_chainloader/src/bsp/raspberrypi/cpu.rs b/07_uart_chainloader/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/07_uart_chainloader/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/07_uart_chainloader/src/bsp/raspberrypi/driver.rs b/07_uart_chainloader/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index fe24dd71b..000000000 --- a/07_uart_chainloader/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/07_uart_chainloader/src/bsp/raspberrypi/link.ld b/07_uart_chainloader/src/bsp/raspberrypi/link.ld deleted file mode 100644 index a6dc653ab..000000000 --- a/07_uart_chainloader/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,53 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set the link address to 32 MiB */ - . = 0x2000000; - - __binary_start = .; - .text : - { - *(.text._start) - KEEP(*(.text.runtime_init)) - *(.text*); - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - .got : - { - *(.got*) - } - - /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ - . = ALIGN(8); - __binary_end_inclusive = . - 8; - - __runtime_init_reloc = runtime_init; - - /DISCARD/ : { *(.comment*) } -} diff --git a/07_uart_chainloader/src/bsp/raspberrypi/memory.rs b/07_uart_chainloader/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 0af09903d..000000000 --- a/07_uart_chainloader/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,103 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __binary_start: UnsafeCell; - static __binary_end_inclusive: UnsafeCell; - static __runtime_init_reloc: UnsafeCell; - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// The address on which the Raspberry firmware loads every binary by default. -#[inline(always)] -pub fn board_default_load_addr() -> *const u64 { - map::BOARD_DEFAULT_LOAD_ADDRESS as _ -} - -/// Return the inclusive range spanning the relocated kernel binary. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn relocated_binary_range_inclusive() -> RangeInclusive<*mut u64> { - unsafe { RangeInclusive::new(__binary_start.get(), __binary_end_inclusive.get()) } -} - -/// The relocated address of function `runtime_init()`. -#[inline(always)] -pub fn relocated_runtime_init_addr() -> *const u64 { - unsafe { __runtime_init_reloc.get() as _ } -} - -/// Return the inclusive range spanning the relocated .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn relocated_bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/07_uart_chainloader/src/console.rs b/07_uart_chainloader/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/07_uart_chainloader/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/07_uart_chainloader/src/cpu.rs b/07_uart_chainloader/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/07_uart_chainloader/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/07_uart_chainloader/src/cpu/smp.rs b/07_uart_chainloader/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/07_uart_chainloader/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/07_uart_chainloader/src/driver.rs b/07_uart_chainloader/src/driver.rs deleted file mode 100644 index e2875b876..000000000 --- a/07_uart_chainloader/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/07_uart_chainloader/src/main.rs b/07_uart_chainloader/src/main.rs deleted file mode 100644 index 6640c754b..000000000 --- a/07_uart_chainloader/src/main.rs +++ /dev/null @@ -1,199 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![feature(asm)] -#![feature(const_fn_fn_ptr_basics)] -#![feature(core_intrinsics)] -#![feature(format_args_nl)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `relocate::relocate_self()`. `relocate::relocate_self()` calls `runtime_init()`, which jumps to -// `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod driver; -mod memory; -mod panic_wait; -mod print; -mod relocate; -mod runtime_init; -mod synchronization; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order. -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; - - println!(" __ __ _ _ _ _ "); - println!("| \\/ (_)_ _ (_) | ___ __ _ __| |"); - println!("| |\\/| | | ' \\| | |__/ _ \\/ _` / _` |"); - println!("|_| |_|_|_||_|_|____\\___/\\__,_\\__,_|"); - println!(); - println!("{:^37}", bsp::board_name()); - println!(); - println!("[ML] Requesting binary"); - console().flush(); - - // Clear the RX FIFOs, if any, of spurious received characters before starting with the loader - // protocol. - console().clear(); - - // Notify `Minipush` to send the binary. - for _ in 0..3 { - console().write_char(3 as char); - } - - // Read the binary's size. - let mut size: u32 = u32::from(console().read_char() as u8); - size |= u32::from(console().read_char() as u8) << 8; - size |= u32::from(console().read_char() as u8) << 16; - size |= u32::from(console().read_char() as u8) << 24; - - // Trust it's not too big. - console().write_char('O'); - console().write_char('K'); - - let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; - unsafe { - // Read the kernel byte by byte. - for i in 0..size { - core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) - } - } - - println!("[ML] Loaded! Executing the payload now\n"); - console().flush(); - - // Use black magic to get a function pointer. - let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; - - // Jump to loaded kernel! - kernel() -} diff --git a/07_uart_chainloader/src/memory.rs b/07_uart_chainloader/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/07_uart_chainloader/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/07_uart_chainloader/src/panic_wait.rs b/07_uart_chainloader/src/panic_wait.rs deleted file mode 100644 index 1386e1e23..000000000 --- a/07_uart_chainloader/src/panic_wait.rs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/07_uart_chainloader/src/print.rs b/07_uart_chainloader/src/print.rs deleted file mode 100644 index 77ebd8b40..000000000 --- a/07_uart_chainloader/src/print.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} diff --git a/07_uart_chainloader/src/relocate.rs b/07_uart_chainloader/src/relocate.rs deleted file mode 100644 index bbedfa475..000000000 --- a/07_uart_chainloader/src/relocate.rs +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Relocation code. - -use crate::{bsp, cpu}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Relocates the own binary from `bsp::memory::board_default_load_addr()` to the `__binary_start` -/// address from the linker script. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - Function must not use the `bss` section. -#[inline(never)] -pub unsafe fn relocate_self() -> ! { - let range = bsp::memory::relocated_binary_range_inclusive(); - let mut relocated_binary_start_addr = *range.start(); - let relocated_binary_end_addr_inclusive = *range.end(); - - // The address of where the previous firmware loaded us. - let mut current_binary_start_addr = bsp::memory::board_default_load_addr(); - - // Copy the whole binary. - while relocated_binary_start_addr <= relocated_binary_end_addr_inclusive { - core::ptr::write_volatile( - relocated_binary_start_addr, - core::ptr::read_volatile(current_binary_start_addr), - ); - relocated_binary_start_addr = relocated_binary_start_addr.offset(1); - current_binary_start_addr = current_binary_start_addr.offset(1); - } - - // The following function calls form a hack to achieve an "absolute jump" to - // `runtime_init::runtime_init()` by forcing an indirection through the global offset table - // (GOT), so that execution continues from the relocated binary. - // - // Without this, the address of `runtime_init()` would be calculated as a relative offset from - // the current program counter, since we are compiling as `position independent code`. This - // would cause us to keep executing from the address to which the firmware loaded us, instead of - // the relocated position. - // - // There likely is a more elegant way to do this. - let relocated_runtime_init_addr = bsp::memory::relocated_runtime_init_addr() as usize; - cpu::branch_to_raw_addr(relocated_runtime_init_addr) -} diff --git a/07_uart_chainloader/src/runtime_init.rs b/07_uart_chainloader/src/runtime_init.rs deleted file mode 100644 index 8ed768d4e..000000000 --- a/07_uart_chainloader/src/runtime_init.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::relocated_bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -#[no_mangle] -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/07_uart_chainloader/src/synchronization.rs b/07_uart_chainloader/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/07_uart_chainloader/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/08_hw_debug_JTAG/.vscode/settings.json b/08_hw_debug_JTAG/.vscode/settings.json new file mode 100644 index 000000000..bfa278e9a --- /dev/null +++ b/08_hw_debug_JTAG/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/08_hw_debug_JTAG/Cargo.lock b/08_hw_debug_JTAG/Cargo.lock new file mode 100644 index 000000000..9020b4f99 --- /dev/null +++ b/08_hw_debug_JTAG/Cargo.lock @@ -0,0 +1,26 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.8.0" +dependencies = [ + "aarch64-cpu", + "tock-registers", +] + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/08_hw_debug_JTAG/Cargo.toml b/08_hw_debug_JTAG/Cargo.toml new file mode 100644 index 000000000..e310c371e --- /dev/null +++ b/08_hw_debug_JTAG/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "mingo" +version = "0.8.0" +authors = ["Andre Richter "] +edition = "2021" + +[profile.release] +lto = true + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] + +[[bin]] +name = "kernel" +path = "src/main.rs" + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/08_hw_debug_JTAG/Makefile b/08_hw_debug_JTAG/Makefile new file mode 100644 index 000000000..9549f0920 --- /dev/null +++ b/08_hw_debug_JTAG/Makefile @@ -0,0 +1,279 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/08_hw_debug_JTAG/README.CN.md b/08_hw_debug_JTAG/README.CN.md new file mode 100644 index 000000000..b77032101 --- /dev/null +++ b/08_hw_debug_JTAG/README.CN.md @@ -0,0 +1,288 @@ +# 教程 08 - 使用JTAG进行硬件调试 + +## tl;dr + +按照以下顺序进行操作: + +1. 运行`make jtagboot`并保持终端打开。 +2. 连接USB串行设备。 +3. 连接`JTAG`调试器的USB设备。 +4. 在新的终端中,运行`make openocd`并保持终端打开。 +5. 在新的终端中,运行`make gdb`或者运行`make gdb-opt0`。 + +![Demo](../doc/09_demo.gif) + +## 目录 + +- [简介](#简介) +- [大纲](#大纲) +- [软件设置](#软件设置) +- [硬件设置](#硬件设置) + * [线路](#线路) +- [准备连接](#准备连接) +- [OpenOCD](#openocd) +- [GDB](#gdb) + * [备注](#备注) + + [优化](#优化) + + [GDB控制](#GDB控制) +- [关于USB连接限制的注意事项](#关于USB连接限制的注意事项) +- [额外资料](#额外资料) +- [致谢](#致谢) +- [相比之前的变化(diff)](#相比之前的变化(diff)) + +## 简介 + +在即将到来的教程中,我们将涉及RPi的SoC(系统芯片)的敏感区域,这可能会让我们的调试工作变得非常困难。 +例如,改变处理器的`Privilege Level`或引入`Virtual Memory`。 + +硬件调试器有时可以成为寻找棘手错误的最后手段。特别是对于调试复杂的、与体系结构相关的硬件问题,它将非常有用, +因为在这个领域,`QEMU`有时无法提供帮助,因为它对硬件的某些特性进行了抽象,并没有模拟到最后一位。 + +那么,让我们介绍一下`JTAG`调试。一旦设置好,它将允许我们在真实的硬件上逐步执行我们的内核。这是多么酷啊! + +## 大纲 + +从内核的角度来看,这个教程与之前的教程相同。我们只是在其周围添加了用于JTAG调试的基础设施。 + +## 软件设置 + +我们需要在SD卡的`config.txt`文件中添加另一行: + +```toml +arm_64bit=1 +init_uart_clock=48000000 +enable_jtag_gpio=1 +``` + +## 硬件设置 + +与我们WG的[Embedded Rust Book]书籍中使用的`STM32F3DISCOVERY`等微控制器板不同,RPi没有在其板上内置调试器。 +因此,您需要购买一个。 + +在本教程中,我们将使用OLIMEX的[ARM-USB-TINY-H]。它具有标准的[ARM JTAG 20 connector]。 +不幸的是,RPi没有这个连接器,所以我们必须通过跳线连接它。 + +[Embedded Rust Book]: https://rust-embedded.github.io/book/start/hardware.html +[ARM-USB-TINY-H]: https://www.olimex.com/Products/ARM/JTAG/ARM-USB-TINY-H +[ARM JTAG 20 connector]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0499dj/BEHEIHCE.html + +### 线路 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO #NameJTAG #NoteDiagram
VTREF1to 3.3V
GND4to GND
22TRST3
26TDI5
27TMS7
25TCK9
23RTCK11
24TDO13
+ +

+ +## 准备连接 + +在启动时,由于我们对`config.txt`进行的更改,RPi的固件将配置相应的GPIO引脚以实现`JTAG`功能。 + +现在剩下的要做的就是暂停RPi的执行,然后通过`JTAG`进行连接。因此,我们添加了一个新的`Makefile` target, +`make jtagboot`,它使用`chainboot`方法将一个小型辅助二进制文件加载到RPi上, +该文件只是将执行核心置于等待状态。 + +文件夹中单独[X1_JTAG_boot]文件夹中单独维护,并且是我们迄今为止在教程中使用的内核的修改版本。 + +[X1_JTAG_boot]: ../X1_JTAG_boot + +```console +$ make jtagboot +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 7 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.394532] Parking CPU core. Please connect over JTAG now. +``` + +保持USB串口连接和打开运行`jtagboot`的终端非常重要。当我们稍后加载实际的内核时,`UART`输出将显示在这里。 + +## OpenOCD + +接下来,我们需要启动开放式片上调试器 [Open On-Chip Debugger],也称为`OpenOCD`,以实际连接`JTAG`。 + +[Open On-Chip Debugger]: http://openocd.org + +一如既往,我们的教程力求使开发工具的使用尽可能简单, +这就是为什么我们将所有内容打包到了[dedicated Docker container]中,该容器已经用于链式引导和`QEMU`。 + +[dedicated Docker container]: ../docker/rustembedded-osdev-utils + +连接Olimex USB JTAG调试器,在同一个文件夹中打开一个新的终端窗口,然后按顺序输入 +`make openocd`命令。你将会看到一些初始输出: + +```console +$ make openocd +[...] +Open On-Chip Debugger 0.10.0 +[...] +Info : Listening on port 6666 for tcl connections +Info : Listening on port 4444 for telnet connections +Info : clock speed 1000 kHz +Info : JTAG tap: rpi3.tap tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4) +Info : rpi3.core0: hardware has 6 breakpoints, 4 watchpoints +Info : rpi3.core1: hardware has 6 breakpoints, 4 watchpoints +Info : rpi3.core2: hardware has 6 breakpoints, 4 watchpoints +Info : rpi3.core3: hardware has 6 breakpoints, 4 watchpoints +Info : Listening on port 3333 for gdb connections +Info : Listening on port 3334 for gdb connections +Info : Listening on port 3335 for gdb connections +Info : Listening on port 3336 for gdb connections +``` + +`OpenOCD`已检测到RPi的四个核心,并打开了四个网络端口,`gdb`现在可以连接到这些端口来调试各自的核心。 + +## GDB + +最后,我们需要一个支持`AArch64`的`gdb`版本。你猜对了,它已经打包在osdev容器中。 +可以通过`make gdb`命令启动它。 + +实际上,这个Makefile target做了更多的事情。它构建了一个包含调试信息的特殊版本的内核。 +这使得`gdb`能够显示我们当前正在调试的`Rust`源代码行。 +它还启动了`gdb`,以便它已经加载了这个调试构建(`kernel_for_jtag`)。 + +现在我们可以使用`gdb`命令行来进行以下操作: + 1. 在我们的内核中设置断点。 + 2. 通过JTAG将内核加载到内存中(请记住,当前RPi仍在执行最小的JTAG引导二进制文件)。 + 3. 操纵RPi的程序计数器,使其从我们内核的入口点开始执行。 + 4. 逐步执行内核的执行过程。 + +```console +$ make gdb +[...] +>>> target remote :3333 # Connect to OpenOCD, core0 +>>> load # Load the kernel into the RPi's DRAM over JTAG. +Loading section .text, size 0x2454 lma 0x80000 +Loading section .rodata, size 0xa1d lma 0x82460 +Loading section .got, size 0x10 lma 0x82e80 +Loading section .data, size 0x20 lma 0x82e90 +Start address 0x0000000000080000, load size 11937 +Transfer rate: 63 KB/sec, 2984 bytes/write. +>>> set $pc = 0x80000 # Set RPI's program counter to the start of the + # kernel binary. +>>> break main.rs:158 +Breakpoint 1 at 0x8025c: file src/main.rs, line 158. +>>> cont +>>> step # Single-step through the kernel +>>> step +>>> ... +``` + +### 备注 + +#### 优化 + +在调试操作系统二进制文件时,您需要在可以逐步执行源代码粒度和生成的二进制文件的优化级别之间进行权衡。 +`make`和`make gdb`targets生成一个`--release`二进制文件,其中包含优化级别为3(`-opt-level=3`)。 +然而,在这种情况下,编译器会非常积极地进行内联,并尽可能地将读取和写入操作打包在一起。 +因此,不总是能够在源代码文件的特定行上准确命中断点。 + +因此,Makefile还提供了`make gdb-opt0` target,它使用了`-opt-level=0`。 +因此,它将允许您拥有更精细的调试粒度。然而,请记住,当调试与硬件密切相关的代码时, +编译器对易失性寄存器的读取或写入进行压缩的优化可能会对执行产生重大影响。 +请注意,上面的演示GIF是使用`gdb-opt0`录制的。 + +#### GDB控制 + +在某些情况下,您可能会遇到延迟循环或等待串行输入的代码。在这种情况下, +逐步执行可能不可行或无法正常工作。您可以通过在这些区域之外设置其他断点,从而跳过这些障碍。 +并使用`cont`命令到达它们。 + +在`gdb`中按下`ctrl+c`将再次停止RPi的执行,以防止您在没有进一步断点的情况下继续执行。 + +## 关于USB连接限制的注意事项 + +如果您按照教程从头到尾进行操作,关于USB连接的一切应该都没问题。 + +但是,请注意,根据当前的形式,我们的`Makefile`对连接的USB设备的命名做出了隐含的假设。 +它期望`/dev/ttyUSB0`是`UART`设备。 + +因此,请确保按照以下顺序将设备连接到您的计算机: + 1. 首先连接USB串行设备。 + 2. 然后连接Olimex调试器。 + +这样,主机操作系统会相应地枚举这些设备。这只需要做一次即可。 +可以多次断开和连接串行设备,例如在保持调试器连接的情况下启动不同的`make jtagboot`运行。 + +## 额外资料 + +- https://metebalci.com/blog/bare-metal-raspberry-pi-3b-jtag +- https://www.suse.com/c/debugging-raspberry-pi-3-with-jtag + +## 致谢 + +感谢[@naotaco](https://github.com/naotaco)为本教程奠定了基础。 + +## 相比之前的变化(diff) +请检查[英文版本](README.md#diff-to-previous),这是最新的。 diff --git a/08_hw_debug_JTAG/README.md b/08_hw_debug_JTAG/README.md new file mode 100644 index 000000000..149282531 --- /dev/null +++ b/08_hw_debug_JTAG/README.md @@ -0,0 +1,426 @@ +# Tutorial 08 - Hardware Debugging using JTAG + +## tl;dr + +In the exact order as listed: + +1. `make jtagboot` and keep terminal open. +2. Connect USB serial device. +3. Connect `JTAG` debugger USB device. +4. In new terminal, `make openocd` and keep terminal open. +5. In new terminal, `make gdb` or make `make gdb-opt0`. + +![Demo](../doc/09_demo.gif) + +## Table of Contents + +- [Introduction](#introduction) +- [Outline](#outline) +- [Software Setup](#software-setup) +- [Hardware Setup](#hardware-setup) + * [Wiring](#wiring) +- [Getting ready to connect](#getting-ready-to-connect) +- [OpenOCD](#openocd) +- [GDB](#gdb) + * [Remarks](#remarks) + + [Optimization](#optimization) + + [GDB control](#gdb-control) +- [Notes on USB connection constraints](#notes-on-usb-connection-constraints) +- [Additional resources](#additional-resources) +- [Acknowledgments](#acknowledgments) +- [Diff to previous](#diff-to-previous) + +## Introduction + +In the upcoming tutorials, we are going to touch sensitive areas of the RPi's SoC that can make our +debugging life very hard. For example, changing the processor's `Privilege Level` or introducing +`Virtual Memory`. + +A hardware based debugger can sometimes be the last resort when searching for a tricky bug. +Especially for debugging intricate, architecture-specific HW issues, it will be handy, because in +this area `QEMU` sometimes can not help, since it abstracts certain features of the HW and doesn't +simulate down to the very last bit. + +So lets introduce `JTAG` debugging. Once set up, it will allow us to single-step through our kernel +on the real HW. How cool is that?! + +## Outline + +From kernel perspective, this tutorial is the same as the previous one. We are just wrapping +infrastructure for JTAG debugging around it. + +## Software Setup + +We need to add another line to the `config.txt` file from the SD Card: + +```toml +arm_64bit=1 +init_uart_clock=48000000 +enable_jtag_gpio=1 +``` + +## Hardware Setup + +Unlike microcontroller boards like the `STM32F3DISCOVERY`, which is used in our WG's [Embedded Rust +Book], the Raspberry Pi does not have an embedded debugger on its board. Hence, you need to buy one. + +For this tutorial, we will use the [ARM-USB-TINY-H] from OLIMEX. It has a standard [ARM JTAG 20 +connector]. Unfortunately, the RPi does not, so we have to connect it via jumper wires. + +[Embedded Rust Book]: https://rust-embedded.github.io/book/start/hardware.html +[ARM-USB-TINY-H]: https://www.olimex.com/Products/ARM/JTAG/ARM-USB-TINY-H +[ARM JTAG 20 connector]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0499dj/BEHEIHCE.html + +### Wiring + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GPIO #NameJTAG #NoteDiagram
VTREF1to 3.3V
GND4to GND
22TRST3
26TDI5
27TMS7
25TCK9
23RTCK11
24TDO13
+ +

+ +## Getting ready to connect + +Upon booting, thanks to the changes we made to `config.txt`, the RPi's firmware will configure the +respective GPIO pins for `JTAG` functionality. + +What is left to do now is to pause the execution of the RPi and then connect +over `JTAG`. Therefore, we add a new `Makefile` target, `make jtagboot`, which +uses the `chainboot` approach to load a tiny helper binary onto the RPi that +just parks the executing core into a waiting state. + +The helper binary is maintained separately in this repository's [X1_JTAG_boot] folder, and is a +modified version of the kernel we used in our tutorials so far. + +[X1_JTAG_boot]: ../X1_JTAG_boot + +```console +$ make jtagboot +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 7 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.394532] Parking CPU core. Please connect over JTAG now. +``` + +It is important to keep the USB serial connected and the terminal with the `jtagboot` open and +running. When we load the actual kernel later, `UART` output will appear here. + +## OpenOCD + +Next, we need to launch the [Open On-Chip Debugger], aka `OpenOCD` to actually connect the `JTAG`. + +[Open On-Chip Debugger]: http://openocd.org + +As always, our tutorials try to be as painless as possible regarding dev-tools, which is why we have +packaged everything into the [dedicated Docker container] that is already used for chainbooting and +`QEMU`. + +[dedicated Docker container]: ../docker/rustembedded-osdev-utils + +Connect the Olimex USB JTAG debugger, open a new terminal and in the same folder, type `make +openocd` (in that order!). You will see some initial output: + +```console +$ make openocd +[...] +Open On-Chip Debugger 0.10.0 +[...] +Info : Listening on port 6666 for tcl connections +Info : Listening on port 4444 for telnet connections +Info : clock speed 1000 kHz +Info : JTAG tap: rpi3.tap tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4) +Info : rpi3.core0: hardware has 6 breakpoints, 4 watchpoints +Info : rpi3.core1: hardware has 6 breakpoints, 4 watchpoints +Info : rpi3.core2: hardware has 6 breakpoints, 4 watchpoints +Info : rpi3.core3: hardware has 6 breakpoints, 4 watchpoints +Info : Listening on port 3333 for gdb connections +Info : Listening on port 3334 for gdb connections +Info : Listening on port 3335 for gdb connections +Info : Listening on port 3336 for gdb connections +``` + +`OpenOCD` has detected the four cores of the RPi, and opened four network ports to which `gdb` can +now connect to debug the respective core. + +## GDB + +Finally, we need an `AArch64`-capable version of `gdb`. You guessed right, it's already packaged in +the osdev container. It can be launched via `make gdb`. + +This Makefile target actually does a little more. It builds a special version of our kernel with +debug information included. This enables `gdb` to show the `Rust` source code line we are currently +debugging. It also launches `gdb` such that it already loads this debug build (`kernel_for_jtag`). + +We can now use the `gdb` commandline to + 1. Set breakpoints in our kernel + 2. Load the kernel via JTAG into memory (remember that currently, the RPi is still executing the + minimal JTAG boot binary). + 3. Manipulate the program counter of the RPi to start execution at our kernel's entry point. + 4. Single-step through its execution. + +```console +$ make gdb +[...] +>>> target remote :3333 # Connect to OpenOCD, core0 +>>> load # Load the kernel into the RPi's DRAM over JTAG. +Loading section .text, size 0x2454 lma 0x80000 +Loading section .rodata, size 0xa1d lma 0x82460 +Loading section .got, size 0x10 lma 0x82e80 +Loading section .data, size 0x20 lma 0x82e90 +Start address 0x0000000000080000, load size 11937 +Transfer rate: 63 KB/sec, 2984 bytes/write. +>>> set $pc = 0x80000 # Set RPI's program counter to the start of the + # kernel binary. +>>> break main.rs:158 +Breakpoint 1 at 0x8025c: file src/main.rs, line 158. +>>> cont +>>> step # Single-step through the kernel +>>> step +>>> ... +``` + +### Remarks + +#### Optimization + +When debugging an OS binary, you have to make a trade-off between the granularity at which you can +step through your Rust source-code and the optimization level of the generated binary. The `make` +and `make gdb` targets produce a `--release` binary, which includes an optimization level of three +(`-opt-level=3`). However, in this case, the compiler will inline very aggressively and pack +together reads and writes where possible. As a result, it will not always be possible to hit +breakpoints exactly where you want to regarding the line of source code file. + +For this reason, the Makefile also provides the `make gdb-opt0` target, which uses `-opt-level=0`. +Hence, it will allow you to have finer debugging granularity. However, please keep in mind that when +debugging code that closely deals with HW, a compiler optimization that squashes reads or writes to +volatile registers can make all the difference in execution. FYI, the demo gif above has been +recorded with `gdb-opt0`. + +#### GDB control + +At some point, you may reach delay loops or code that waits on user input from the serial. Here, +single stepping might not be feasible or work anymore. You can jump over these roadblocks by setting +other breakpoints beyond these areas, and reach them using the `cont` command. + +Pressing `ctrl+c` in `gdb` will stop execution of the RPi again in case you continued it without +further breakpoints. + +## Notes on USB connection constraints + +If you followed the tutorial from top to bottom, everything should be fine regarding USB +connections. + +Still, please note that in its current form, our `Makefile` makes implicit assumptions about the +naming of the connected USB devices. It expects `/dev/ttyUSB0` to be the `UART` device. + +Hence, please ensure the following order of connecting the devices to your box: + 1. Connect the USB serial. + 2. Afterwards, the Olimex debugger. + +This way, the host OS enumerates the devices accordingly. This has to be done only once. It is fine +to disconnect and connect the serial multiple times, e.g. for kicking off different `make jtagboot` +runs, while keeping the debugger connected. + +## Additional resources + +- https://metebalci.com/blog/bare-metal-raspberry-pi-3b-jtag +- https://www.suse.com/c/debugging-raspberry-pi-3-with-jtag + +## Acknowledgments + +Thanks to [@naotaco](https://github.com/naotaco) for laying the groundwork for this tutorial. + +## Diff to previous +```diff + +diff -uNr 07_timestamps/Cargo.toml 08_hw_debug_JTAG/Cargo.toml +--- 07_timestamps/Cargo.toml ++++ 08_hw_debug_JTAG/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.7.0" ++version = "0.8.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 07_timestamps/Makefile 08_hw_debug_JTAG/Makefile +--- 07_timestamps/Makefile ++++ 08_hw_debug_JTAG/Makefile +@@ -32,6 +32,8 @@ + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf ++ OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg ++ JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 + else ifeq ($(BSP),rpi4) +@@ -43,6 +45,8 @@ + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf ++ OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg ++ JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 + endif +@@ -99,18 +103,25 @@ + DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial + DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i + DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common ++DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot + DOCKER_ARG_DEV = --privileged -v /dev:/dev ++DOCKER_ARG_NET = --network host + + # DOCKER_IMAGE defined in include file (see top of this file). + DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) + DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) + DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) ++DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + + # Dockerize commands, which require USB device passthrough, only on Linux. + ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) ++ DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) ++ DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) ++else ++ DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# + endif + + +@@ -215,6 +226,35 @@ + + + ++##-------------------------------------------------------------------------------------------------- ++## Debugging targets ++##-------------------------------------------------------------------------------------------------- ++.PHONY: jtagboot openocd gdb gdb-opt0 ++ ++##------------------------------------------------------------------------------ ++## Push the JTAG boot image to the real HW target ++##------------------------------------------------------------------------------ ++jtagboot: ++ @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ++ ++##------------------------------------------------------------------------------ ++## Start OpenOCD session ++##------------------------------------------------------------------------------ ++openocd: ++ $(call color_header, "Launching OpenOCD") ++ @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ++ ++##------------------------------------------------------------------------------ ++## Start GDB session ++##------------------------------------------------------------------------------ ++gdb: RUSTC_MISC_ARGS += -C debuginfo=2 ++gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 ++gdb gdb-opt0: $(KERNEL_ELF) ++ $(call color_header, "Launching GDB") ++ @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ++ ++ ++ + ##-------------------------------------------------------------------------------------------------- + ## Testing targets + ##-------------------------------------------------------------------------------------------------- + +diff -uNr 07_timestamps/src/bsp/raspberrypi/driver.rs 08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs +--- 07_timestamps/src/bsp/raspberrypi/driver.rs ++++ 08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs +@@ -57,17 +57,6 @@ + /// # Safety + /// + /// See child function calls. +-/// +-/// # Note +-/// +-/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +-/// +-/// On `AArch64`, which is the only implemented architecture at the time of writing this, +-/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +-/// instructions. They are therefore safe to use even with MMU + caching deactivated. +-/// +-/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +-/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store + pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + +``` diff --git a/08_hw_debug_JTAG/build.rs b/08_hw_debug_JTAG/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/08_hw_debug_JTAG/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/08_hw_debug_JTAG/src/_arch/aarch64/cpu.rs b/08_hw_debug_JTAG/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..602c9789c --- /dev/null +++ b/08_hw_debug_JTAG/src/_arch/aarch64/cpu.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff --git a/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs b/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..2a6c46492 --- /dev/null +++ b/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff --git a/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s b/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..0b801b4bd --- /dev/null +++ b/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed on the boot core. Park it otherwise. + mrs x0, MPIDR_EL1 + and x0, x0, {CONST_CORE_ID_MASK} + ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x0, x1 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/08_hw_debug_JTAG/src/_arch/aarch64/time.rs b/08_hw_debug_JTAG/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/08_hw_debug_JTAG/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/08_hw_debug_JTAG/src/bsp.rs b/08_hw_debug_JTAG/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/08_hw_debug_JTAG/src/bsp/device_driver.rs b/08_hw_debug_JTAG/src/bsp/device_driver.rs new file mode 100644 index 000000000..64049a4cf --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/08_hw_debug_JTAG/src/bsp/device_driver/bcm.rs b/08_hw_debug_JTAG/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..1c343d1d7 --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/08_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/08_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..8e57dfedb --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/08_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/08_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..d92612ea8 --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff --git a/08_hw_debug_JTAG/src/bsp/device_driver/common.rs b/08_hw_debug_JTAG/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..dfe7d8ef3 --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..3ea864dc7 --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..2a80ee2c5 --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi/kernel.ld b/08_hw_debug_JTAG/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..f6c188434 --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..cdca14b8a --- /dev/null +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } +} diff --git a/08_hw_debug_JTAG/src/console.rs b/08_hw_debug_JTAG/src/console.rs new file mode 100644 index 000000000..a83f86fe0 --- /dev/null +++ b/08_hw_debug_JTAG/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization::{self, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) +} diff --git a/08_hw_debug_JTAG/src/console/null_console.rs b/08_hw_debug_JTAG/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/08_hw_debug_JTAG/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/08_hw_debug_JTAG/src/cpu.rs b/08_hw_debug_JTAG/src/cpu.rs new file mode 100644 index 000000000..67ab79c08 --- /dev/null +++ b/08_hw_debug_JTAG/src/cpu.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; diff --git a/08_hw_debug_JTAG/src/cpu/boot.rs b/08_hw_debug_JTAG/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/08_hw_debug_JTAG/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/08_hw_debug_JTAG/src/driver.rs b/08_hw_debug_JTAG/src/driver.rs new file mode 100644 index 000000000..050e7022f --- /dev/null +++ b/08_hw_debug_JTAG/src/driver.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + info, + synchronization::{interface::Mutex, NullLock}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/08_hw_debug_JTAG/src/main.rs b/08_hw_debug_JTAG/src/main.rs new file mode 100644 index 000000000..b094dacc5 --- /dev/null +++ b/08_hw_debug_JTAG/src/main.rs @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(format_args_nl)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_main] +#![no_std] + +mod bsp; +mod console; +mod cpu; +mod driver; +mod panic_wait; +mod print; +mod synchronization; +mod time; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order. +unsafe fn kernel_init() -> ! { + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + use core::time::Duration; + + info!( + "{} version {}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + info!("Booting on: {}", bsp::board_name()); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + // Test a failing timer case. + time::time_manager().spin_for(Duration::from_nanos(1)); + + loop { + info!("Spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); + } +} diff --git a/08_hw_debug_JTAG/src/panic_wait.rs b/08_hw_debug_JTAG/src/panic_wait.rs new file mode 100644 index 000000000..5776aca87 --- /dev/null +++ b/08_hw_debug_JTAG/src/panic_wait.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + cpu::wait_forever() +} diff --git a/08_hw_debug_JTAG/src/print.rs b/08_hw_debug_JTAG/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/08_hw_debug_JTAG/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/08_hw_debug_JTAG/src/synchronization.rs b/08_hw_debug_JTAG/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/08_hw_debug_JTAG/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/08_hw_debug_JTAG/src/time.rs b/08_hw_debug_JTAG/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/08_hw_debug_JTAG/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/08_hw_debug_JTAG/tests/boot_test_string.rb b/08_hw_debug_JTAG/tests/boot_test_string.rb new file mode 100644 index 000000000..02c3c492a --- /dev/null +++ b/08_hw_debug_JTAG/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Spinning for 1 second' diff --git a/08_timestamps/.vscode/settings.json b/08_timestamps/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/08_timestamps/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/08_timestamps/Cargo.lock b/08_timestamps/Cargo.lock deleted file mode 100644 index 7b2456e16..000000000 --- a/08_timestamps/Cargo.lock +++ /dev/null @@ -1,33 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "register", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/08_timestamps/Cargo.toml b/08_timestamps/Cargo.toml deleted file mode 100644 index b8906da1f..000000000 --- a/08_timestamps/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Optional dependencies -register = { version = "1.x.x", optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/08_timestamps/Makefile b/08_timestamps/Makefile deleted file mode 100644 index 2f04337ed..000000000 --- a/08_timestamps/Makefile +++ /dev/null @@ -1,117 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DEV = --privileged -v /dev:/dev - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot clippy clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -endif - -chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/08_timestamps/README.md b/08_timestamps/README.md deleted file mode 100644 index b1244dcec..000000000 --- a/08_timestamps/README.md +++ /dev/null @@ -1,757 +0,0 @@ -# Tutorial 08 - Timestamps - -## tl;dr - -- We add abstractions for the architectural timer, implement it for `aarch64` and use it to annotate - prints with timestamps. -- A `warn!()` macro is added. - -## Test it - -Check it out via chainboot (added in previous tutorial): -```console -$ make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 3 - -[ML] Requesting binary -[MP] ⏩ Pushing 12 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 -[ML] Loaded! Executing the payload now - -[ 0.586140] Booting on: Raspberry Pi 3 -[ 0.587227] Architectural timer resolution: 52 ns -[ 0.589530] Drivers loaded: -[ 0.590876] 1. BCM GPIO -[ 0.592309] 2. BCM PL011 UART -[W 0.594005] Spin duration smaller than architecturally supported, skipping -[ 0.597392] Spinning for 1 second -[ 1.599001] Spinning for 1 second -[ 2.599872] Spinning for 1 second - -``` - -## Diff to previous -```diff -Binary files 07_uart_chainloader/demo_payload_rpi3.img and 08_timestamps/demo_payload_rpi3.img differ -Binary files 07_uart_chainloader/demo_payload_rpi4.img and 08_timestamps/demo_payload_rpi4.img differ - -diff -uNr 07_uart_chainloader/Makefile 08_timestamps/Makefile ---- 07_uart_chainloader/Makefile -+++ 08_timestamps/Makefile -@@ -21,8 +21,7 @@ - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld -- RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -C relocation-model=pic -- CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img -+ RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 - else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img -@@ -32,8 +31,7 @@ - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld -- RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -C relocation-model=pic -- CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img -+ RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 - endif - - # Export for build.rs -@@ -75,8 +73,7 @@ - EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) - EXEC_MINIPUSH = ruby ../utils/minipush.rb - --.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu qemuasm chainboot clippy clean readelf objdump nm \ -- check -+.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot clippy clean readelf objdump nm check - - all: $(KERNEL_BIN) - -@@ -90,18 +87,15 @@ - $(DOC_CMD) --document-private-items --open - - ifeq ($(QEMU_MACHINE_TYPE),) --qemu qemuasm: -+qemu: - @echo "This board is not yet supported for QEMU." - else - qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -- --qemuasm: $(KERNEL_BIN) -- @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm - endif - --chainboot: -- @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) -+chainboot: $(KERNEL_BIN) -+ @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - - clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) -@@ -113,10 +107,7 @@ - readelf --headers $(KERNEL_ELF) - - objdump: $(KERNEL_ELF) -- @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ -- --section .text \ -- --section .got \ -- $(KERNEL_ELF) | rustfilt -+ @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - - nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -diff -uNr 07_uart_chainloader/src/_arch/aarch64/cpu.rs 08_timestamps/src/_arch/aarch64/cpu.rs ---- 07_uart_chainloader/src/_arch/aarch64/cpu.rs -+++ 08_timestamps/src/_arch/aarch64/cpu.rs -@@ -21,12 +21,12 @@ - #[naked] - #[no_mangle] - pub unsafe fn _start() -> ! { -- use crate::relocate; -+ use crate::runtime_init; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); -- relocate::relocate_self() -+ runtime_init::runtime_init() - } else { - // If not core0, infinitely wait for events. - wait_forever() -@@ -39,15 +39,6 @@ - - pub use asm::nop; - --/// Spin for `n` cycles. --#[cfg(feature = "bsp_rpi3")] --#[inline(always)] --pub fn spin_for_cycles(n: usize) { -- for _ in 0..n { -- asm::nop(); -- } --} -- - /// Pause execution on the core. - #[inline(always)] - pub fn wait_forever() -> ! { -@@ -55,19 +46,3 @@ - asm::wfe() - } - } -- --/// Branch to a raw integer value. --/// --/// # Safety --/// --/// - This is highly unsafe. Use with care. --#[inline(always)] --pub unsafe fn branch_to_raw_addr(addr: usize) -> ! { -- asm!( -- "blr {destination:x}", -- destination = in(reg) addr, -- options(nomem, nostack) -- ); -- -- core::intrinsics::unreachable() --} - -diff -uNr 07_uart_chainloader/src/_arch/aarch64/time.rs 08_timestamps/src/_arch/aarch64/time.rs ---- 07_uart_chainloader/src/_arch/aarch64/time.rs -+++ 08_timestamps/src/_arch/aarch64/time.rs -@@ -0,0 +1,98 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Architectural timer primitives. -+ -+use crate::{time, warn}; -+use core::time::Duration; -+use cortex_a::regs::*; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+const NS_PER_S: u64 = 1_000_000_000; -+ -+/// ARMv8 Generic Timer. -+struct GenericTimer; -+ -+//-------------------------------------------------------------------------------------------------- -+// Global instances -+//-------------------------------------------------------------------------------------------------- -+ -+static TIME_MANAGER: GenericTimer = GenericTimer; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return a reference to the time manager. -+pub fn time_manager() -> &'static impl time::interface::TimeManager { -+ &TIME_MANAGER -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+ -+impl time::interface::TimeManager for GenericTimer { -+ fn resolution(&self) -> Duration { -+ Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) -+ } -+ -+ fn uptime(&self) -> Duration { -+ let frq: u64 = CNTFRQ_EL0.get() as u64; -+ let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; -+ -+ Duration::from_nanos(current_count / frq) -+ } -+ -+ fn spin_for(&self, duration: Duration) { -+ // Instantly return on zero. -+ if duration.as_nanos() == 0 { -+ return; -+ } -+ -+ // Calculate the register compare value. -+ let frq = CNTFRQ_EL0.get() as u64; -+ let x = match frq.checked_mul(duration.as_nanos() as u64) { -+ None => { -+ warn!("Spin duration too long, skipping"); -+ return; -+ } -+ Some(val) => val, -+ }; -+ let tval = x / NS_PER_S; -+ -+ // Check if it is within supported bounds. -+ let warn: Option<&str> = if tval == 0 { -+ Some("smaller") -+ // The upper 32 bits of CNTP_TVAL_EL0 are reserved. -+ } else if tval > u32::max_value().into() { -+ Some("bigger") -+ } else { -+ None -+ }; -+ -+ if let Some(w) = warn { -+ warn!( -+ "Spin duration {} than architecturally supported, skipping", -+ w -+ ); -+ return; -+ } -+ -+ // Set the compare value register. -+ CNTP_TVAL_EL0.set(tval); -+ -+ // Kick off the counting. // Disable timer interrupt. -+ CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); -+ -+ // ISTATUS will be '1' when cval ticks have passed. Busy-check it. -+ while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} -+ -+ // Disable counting again. -+ CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); -+ } -+} - -diff -uNr 07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ---- 07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -+++ 08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -@@ -139,25 +139,19 @@ - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { -- use crate::cpu; -+ use crate::{time, time::interface::TimeManager}; -+ use core::time::Duration; - -- // Make an educated guess for a good delay value (Sequence described in the BCM2837 -- // peripherals PDF). -- // -- // - According to Wikipedia, the fastest Pi3 clocks around 1.4 GHz. -- // - The Linux 2837 GPIO driver waits 1 µs between the steps. -- // -- // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs -- // would the CPU be clocked at 2 GHz. -- const DELAY: usize = 2000; -+ // The Linux 2837 GPIO driver waits 1 µs between the steps. -+ const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); -- cpu::spin_for_cycles(DELAY); -+ time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); -- cpu::spin_for_cycles(DELAY); -+ time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - -diff -uNr 07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ---- 07_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -+++ 08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -@@ -287,11 +287,18 @@ - cpu::nop(); - } - -+ // Read one character. -+ let mut ret = inner.registers.DR.get() as u8 as char; -+ -+ // Convert carrige return to newline. -+ if ret == '\r' { -+ ret = '\n' -+ } -+ - // Update statistics. - inner.chars_read += 1; - -- // Read one character. -- inner.registers.DR.get() as u8 as char -+ ret - }) - } - - -diff -uNr 07_uart_chainloader/src/bsp/raspberrypi/link.ld 08_timestamps/src/bsp/raspberrypi/link.ld ---- 07_uart_chainloader/src/bsp/raspberrypi/link.ld -+++ 08_timestamps/src/bsp/raspberrypi/link.ld -@@ -5,15 +5,12 @@ - - SECTIONS - { -- /* Set the link address to 32 MiB */ -- . = 0x2000000; -+ /* Set current address to the value from which the RPi starts execution */ -+ . = 0x80000; - -- __binary_start = .; - .text : - { -- *(.text._start) -- KEEP(*(.text.runtime_init)) -- *(.text*); -+ *(.text._start) *(.text*) - } - - .rodata : -@@ -38,16 +35,5 @@ - __bss_end_inclusive = . - 8; - } - -- .got : -- { -- *(.got*) -- } -- -- /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ -- . = ALIGN(8); -- __binary_end_inclusive = . - 8; -- -- __runtime_init_reloc = runtime_init; -- - /DISCARD/ : { *(.comment*) } - } - -diff -uNr 07_uart_chainloader/src/bsp/raspberrypi/memory.rs 08_timestamps/src/bsp/raspberrypi/memory.rs ---- 07_uart_chainloader/src/bsp/raspberrypi/memory.rs -+++ 08_timestamps/src/bsp/raspberrypi/memory.rs -@@ -12,9 +12,6 @@ - - // Symbols from the linker script. - extern "Rust" { -- static __binary_start: UnsafeCell; -- static __binary_end_inclusive: UnsafeCell; -- static __runtime_init_reloc: UnsafeCell; - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; - } -@@ -26,12 +23,10 @@ - /// The board's memory map. - #[rustfmt::skip] - pub(super) mod map { -- pub const BOOT_CORE_STACK_END: usize = 0x8_0000; -+ pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - -- pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; -- -- pub const GPIO_OFFSET: usize = 0x0020_0000; -- pub const UART_OFFSET: usize = 0x0020_1000; -+ pub const GPIO_OFFSET: usize = 0x0020_0000; -+ pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] -@@ -64,35 +59,13 @@ - map::BOOT_CORE_STACK_END - } - --/// The address on which the Raspberry firmware loads every binary by default. --#[inline(always)] --pub fn board_default_load_addr() -> *const u64 { -- map::BOARD_DEFAULT_LOAD_ADDRESS as _ --} -- --/// Return the inclusive range spanning the relocated kernel binary. --/// --/// # Safety --/// --/// - Values are provided by the linker script and must be trusted as-is. --/// - The linker-provided addresses must be u64 aligned. --pub fn relocated_binary_range_inclusive() -> RangeInclusive<*mut u64> { -- unsafe { RangeInclusive::new(__binary_start.get(), __binary_end_inclusive.get()) } --} -- --/// The relocated address of function `runtime_init()`. --#[inline(always)] --pub fn relocated_runtime_init_addr() -> *const u64 { -- unsafe { __runtime_init_reloc.get() as _ } --} -- --/// Return the inclusive range spanning the relocated .bss section. -+/// Return the inclusive range spanning the .bss section. - /// - /// # Safety - /// - /// - Values are provided by the linker script and must be trusted as-is. - /// - The linker-provided addresses must be u64 aligned. --pub fn relocated_bss_range_inclusive() -> RangeInclusive<*mut u64> { -+pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - -diff -uNr 07_uart_chainloader/src/main.rs 08_timestamps/src/main.rs ---- 07_uart_chainloader/src/main.rs -+++ 08_timestamps/src/main.rs -@@ -11,9 +11,11 @@ - //! - //! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. - //! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -+//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. - //! - //! [console interface]: ../libkernel/console/interface/index.html - //! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -+//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html - //! - //! # Code organization and architecture - //! -@@ -100,9 +102,7 @@ - //! - `crate::memory::*` - //! - `crate::bsp::memory::*` - --#![feature(asm)] - #![feature(const_fn_fn_ptr_basics)] --#![feature(core_intrinsics)] - #![feature(format_args_nl)] - #![feature(naked_functions)] - #![feature(panic_info_message)] -@@ -111,8 +111,7 @@ - #![no_std] - - // `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls --// `relocate::relocate_self()`. `relocate::relocate_self()` calls `runtime_init()`, which jumps to --// `kernel_init()`. -+// `runtime_init()`, which jumps to `kernel_init()`. - - mod bsp; - mod console; -@@ -121,9 +120,9 @@ - mod memory; - mod panic_wait; - mod print; --mod relocate; - mod runtime_init; - mod synchronization; -+mod time; - - /// Early init code. - /// -@@ -148,52 +147,31 @@ - - /// The main function running after the early init. - fn kernel_main() -> ! { -- use bsp::console::console; -- use console::interface::All; -+ use core::time::Duration; -+ use driver::interface::DriverManager; -+ use time::interface::TimeManager; - -- println!(" __ __ _ _ _ _ "); -- println!("| \\/ (_)_ _ (_) | ___ __ _ __| |"); -- println!("| |\\/| | | ' \\| | |__/ _ \\/ _` / _` |"); -- println!("|_| |_|_|_||_|_|____\\___/\\__,_\\__,_|"); -- println!(); -- println!("{:^37}", bsp::board_name()); -- println!(); -- println!("[ML] Requesting binary"); -- console().flush(); -- -- // Clear the RX FIFOs, if any, of spurious received characters before starting with the loader -- // protocol. -- console().clear(); -- -- // Notify `Minipush` to send the binary. -- for _ in 0..3 { -- console().write_char(3 as char); -- } -+ info!("Booting on: {}", bsp::board_name()); - -- // Read the binary's size. -- let mut size: u32 = u32::from(console().read_char() as u8); -- size |= u32::from(console().read_char() as u8) << 8; -- size |= u32::from(console().read_char() as u8) << 16; -- size |= u32::from(console().read_char() as u8) << 24; -- -- // Trust it's not too big. -- console().write_char('O'); -- console().write_char('K'); -- -- let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; -- unsafe { -- // Read the kernel byte by byte. -- for i in 0..size { -- core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) -- } -+ info!( -+ "Architectural timer resolution: {} ns", -+ time::time_manager().resolution().as_nanos() -+ ); -+ -+ info!("Drivers loaded:"); -+ for (i, driver) in bsp::driver::driver_manager() -+ .all_device_drivers() -+ .iter() -+ .enumerate() -+ { -+ info!(" {}. {}", i + 1, driver.compatible()); - } - -- println!("[ML] Loaded! Executing the payload now\n"); -- console().flush(); -+ // Test a failing timer case. -+ time::time_manager().spin_for(Duration::from_nanos(1)); - -- // Use black magic to get a function pointer. -- let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; -- -- // Jump to loaded kernel! -- kernel() -+ loop { -+ info!("Spinning for 1 second"); -+ time::time_manager().spin_for(Duration::from_secs(1)); -+ } - } - -diff -uNr 07_uart_chainloader/src/print.rs 08_timestamps/src/print.rs ---- 07_uart_chainloader/src/print.rs -+++ 08_timestamps/src/print.rs -@@ -36,3 +36,71 @@ - $crate::print::_print(format_args_nl!($($arg)*)); - }) - } -+ -+/// Prints an info, with a newline. -+#[macro_export] -+macro_rules! info { -+ ($string:expr) => ({ -+ #[allow(unused_imports)] -+ use crate::time::interface::TimeManager; -+ -+ let timestamp = $crate::time::time_manager().uptime(); -+ let timestamp_subsec_us = timestamp.subsec_micros(); -+ -+ $crate::print::_print(format_args_nl!( -+ concat!("[ {:>3}.{:03}{:03}] ", $string), -+ timestamp.as_secs(), -+ timestamp_subsec_us / 1_000, -+ timestamp_subsec_us modulo 1_000 -+ )); -+ }); -+ ($format_string:expr, $($arg:tt)*) => ({ -+ #[allow(unused_imports)] -+ use crate::time::interface::TimeManager; -+ -+ let timestamp = $crate::time::time_manager().uptime(); -+ let timestamp_subsec_us = timestamp.subsec_micros(); -+ -+ $crate::print::_print(format_args_nl!( -+ concat!("[ {:>3}.{:03}{:03}] ", $format_string), -+ timestamp.as_secs(), -+ timestamp_subsec_us / 1_000, -+ timestamp_subsec_us modulo 1_000, -+ $($arg)* -+ )); -+ }) -+} -+ -+/// Prints a warning, with a newline. -+#[macro_export] -+macro_rules! warn { -+ ($string:expr) => ({ -+ #[allow(unused_imports)] -+ use crate::time::interface::TimeManager; -+ -+ let timestamp = $crate::time::time_manager().uptime(); -+ let timestamp_subsec_us = timestamp.subsec_micros(); -+ -+ $crate::print::_print(format_args_nl!( -+ concat!("[W {:>3}.{:03}{:03}] ", $string), -+ timestamp.as_secs(), -+ timestamp_subsec_us / 1_000, -+ timestamp_subsec_us modulo 1_000 -+ )); -+ }); -+ ($format_string:expr, $($arg:tt)*) => ({ -+ #[allow(unused_imports)] -+ use crate::time::interface::TimeManager; -+ -+ let timestamp = $crate::time::time_manager().uptime(); -+ let timestamp_subsec_us = timestamp.subsec_micros(); -+ -+ $crate::print::_print(format_args_nl!( -+ concat!("[W {:>3}.{:03}{:03}] ", $format_string), -+ timestamp.as_secs(), -+ timestamp_subsec_us / 1_000, -+ timestamp_subsec_us modulo 1_000, -+ $($arg)* -+ )); -+ }) -+} - -diff -uNr 07_uart_chainloader/src/relocate.rs 08_timestamps/src/relocate.rs ---- 07_uart_chainloader/src/relocate.rs -+++ 08_timestamps/src/relocate.rs -@@ -1,51 +0,0 @@ --// SPDX-License-Identifier: MIT OR Apache-2.0 --// --// Copyright (c) 2018-2020 Andre Richter -- --//! Relocation code. -- --use crate::{bsp, cpu}; -- --//-------------------------------------------------------------------------------------------------- --// Public Code --//-------------------------------------------------------------------------------------------------- -- --/// Relocates the own binary from `bsp::memory::board_default_load_addr()` to the `__binary_start` --/// address from the linker script. --/// --/// # Safety --/// --/// - Only a single core must be active and running this function. --/// - Function must not use the `bss` section. --#[inline(never)] --pub unsafe fn relocate_self() -> ! { -- let range = bsp::memory::relocated_binary_range_inclusive(); -- let mut relocated_binary_start_addr = *range.start(); -- let relocated_binary_end_addr_inclusive = *range.end(); -- -- // The address of where the previous firmware loaded us. -- let mut current_binary_start_addr = bsp::memory::board_default_load_addr(); -- -- // Copy the whole binary. -- while relocated_binary_start_addr <= relocated_binary_end_addr_inclusive { -- core::ptr::write_volatile( -- relocated_binary_start_addr, -- core::ptr::read_volatile(current_binary_start_addr), -- ); -- relocated_binary_start_addr = relocated_binary_start_addr.offset(1); -- current_binary_start_addr = current_binary_start_addr.offset(1); -- } -- -- // The following function calls form a hack to achieve an "absolute jump" to -- // `runtime_init::runtime_init()` by forcing an indirection through the global offset table -- // (GOT), so that execution continues from the relocated binary. -- // -- // Without this, the address of `runtime_init()` would be calculated as a relative offset from -- // the current program counter, since we are compiling as `position independent code`. This -- // would cause us to keep executing from the address to which the firmware loaded us, instead of -- // the relocated position. -- // -- // There likely is a more elegant way to do this. -- let relocated_runtime_init_addr = bsp::memory::relocated_runtime_init_addr() as usize; -- cpu::branch_to_raw_addr(relocated_runtime_init_addr) --} - -diff -uNr 07_uart_chainloader/src/runtime_init.rs 08_timestamps/src/runtime_init.rs ---- 07_uart_chainloader/src/runtime_init.rs -+++ 08_timestamps/src/runtime_init.rs -@@ -17,7 +17,7 @@ - /// - Must only be called pre `kernel_init()`. - #[inline(always)] - unsafe fn zero_bss() { -- memory::zero_volatile(bsp::memory::relocated_bss_range_inclusive()); -+ memory::zero_volatile(bsp::memory::bss_range_inclusive()); - } - - //-------------------------------------------------------------------------------------------------- -@@ -30,7 +30,6 @@ - /// # Safety - /// - /// - Only a single core must be active and running this function. --#[no_mangle] - pub unsafe fn runtime_init() -> ! { - zero_bss(); - - -diff -uNr 07_uart_chainloader/src/time.rs 08_timestamps/src/time.rs ---- 07_uart_chainloader/src/time.rs -+++ 08_timestamps/src/time.rs -@@ -0,0 +1,35 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Timer primitives. -+ -+#[cfg(target_arch = "aarch64")] -+#[path = "_arch/aarch64/time.rs"] -+mod arch_time; -+pub use arch_time::*; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Timekeeping interfaces. -+pub mod interface { -+ use core::time::Duration; -+ -+ /// Time management functions. -+ /// -+ /// The `BSP` is supposed to supply one global instance. -+ pub trait TimeManager { -+ /// The timer's resolution. -+ fn resolution(&self) -> Duration; -+ -+ /// The uptime since power-on of the device. -+ /// -+ /// This includes time consumed by firmware and bootloaders. -+ fn uptime(&self) -> Duration; -+ -+ /// Spin for a given duration. -+ fn spin_for(&self, duration: Duration); -+ } -+} - -``` diff --git a/08_timestamps/build.rs b/08_timestamps/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/08_timestamps/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/08_timestamps/src/_arch/aarch64/cpu.rs b/08_timestamps/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 3f502ee02..000000000 --- a/08_timestamps/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - use crate::runtime_init; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); - runtime_init::runtime_init() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} diff --git a/08_timestamps/src/_arch/aarch64/cpu/smp.rs b/08_timestamps/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/08_timestamps/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/08_timestamps/src/_arch/aarch64/time.rs b/08_timestamps/src/_arch/aarch64/time.rs deleted file mode 100644 index af98ddd01..000000000 --- a/08_timestamps/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) - } - - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; - - Duration::from_nanos(current_count / frq) - } - - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } - - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get() as u64; - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; - } - - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); - - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); - - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} - - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); - } -} diff --git a/08_timestamps/src/bsp.rs b/08_timestamps/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/08_timestamps/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/08_timestamps/src/bsp/device_driver.rs b/08_timestamps/src/bsp/device_driver.rs deleted file mode 100644 index ce7396f22..000000000 --- a/08_timestamps/src/bsp/device_driver.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/08_timestamps/src/bsp/device_driver/bcm.rs b/08_timestamps/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 59071d5d8..000000000 --- a/08_timestamps/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index 15bd3b78b..000000000 --- a/08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; - use core::time::Duration; - - // The Linux 2837 GPIO driver waits 1 µs between the steps. - const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index e39bc7cdb..000000000 --- a/08_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,323 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => _reserved3), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Read one character. - let mut ret = inner.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - inner.chars_read += 1; - - ret - }) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} diff --git a/08_timestamps/src/bsp/device_driver/common.rs b/08_timestamps/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/08_timestamps/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/08_timestamps/src/bsp/raspberrypi.rs b/08_timestamps/src/bsp/raspberrypi.rs deleted file mode 100644 index 10888d37f..000000000 --- a/08_timestamps/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/08_timestamps/src/bsp/raspberrypi/console.rs b/08_timestamps/src/bsp/raspberrypi/console.rs deleted file mode 100644 index d1b60dd82..000000000 --- a/08_timestamps/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} diff --git a/08_timestamps/src/bsp/raspberrypi/cpu.rs b/08_timestamps/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/08_timestamps/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/08_timestamps/src/bsp/raspberrypi/driver.rs b/08_timestamps/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index fe24dd71b..000000000 --- a/08_timestamps/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/08_timestamps/src/bsp/raspberrypi/link.ld b/08_timestamps/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/08_timestamps/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/08_timestamps/src/bsp/raspberrypi/memory.rs b/08_timestamps/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index fae051257..000000000 --- a/08_timestamps/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/08_timestamps/src/console.rs b/08_timestamps/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/08_timestamps/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/08_timestamps/src/cpu.rs b/08_timestamps/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/08_timestamps/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/08_timestamps/src/cpu/smp.rs b/08_timestamps/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/08_timestamps/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/08_timestamps/src/driver.rs b/08_timestamps/src/driver.rs deleted file mode 100644 index e2875b876..000000000 --- a/08_timestamps/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/08_timestamps/src/main.rs b/08_timestamps/src/main.rs deleted file mode 100644 index 2c9f1fb7f..000000000 --- a/08_timestamps/src/main.rs +++ /dev/null @@ -1,177 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![feature(const_fn_fn_ptr_basics)] -#![feature(format_args_nl)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod driver; -mod memory; -mod panic_wait; -mod print; -mod runtime_init; -mod synchronization; -mod time; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order. -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; - - info!("Booting on: {}", bsp::board_name()); - - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() - ); - - info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } - - // Test a failing timer case. - time::time_manager().spin_for(Duration::from_nanos(1)); - - loop { - info!("Spinning for 1 second"); - time::time_manager().spin_for(Duration::from_secs(1)); - } -} diff --git a/08_timestamps/src/memory.rs b/08_timestamps/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/08_timestamps/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/08_timestamps/src/panic_wait.rs b/08_timestamps/src/panic_wait.rs deleted file mode 100644 index 1386e1e23..000000000 --- a/08_timestamps/src/panic_wait.rs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/08_timestamps/src/print.rs b/08_timestamps/src/print.rs deleted file mode 100644 index 8b6f3f988..000000000 --- a/08_timestamps/src/print.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} - -/// Prints an info, with a newline. -#[macro_export] -macro_rules! info { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} - -/// Prints a warning, with a newline. -#[macro_export] -macro_rules! warn { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} diff --git a/08_timestamps/src/runtime_init.rs b/08_timestamps/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/08_timestamps/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/08_timestamps/src/synchronization.rs b/08_timestamps/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/08_timestamps/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/08_timestamps/src/time.rs b/08_timestamps/src/time.rs deleted file mode 100644 index cd3ceec33..000000000 --- a/08_timestamps/src/time.rs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; -pub use arch_time::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); - } -} diff --git a/09_hw_debug_JTAG/.vscode/settings.json b/09_hw_debug_JTAG/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/09_hw_debug_JTAG/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/09_hw_debug_JTAG/Cargo.lock b/09_hw_debug_JTAG/Cargo.lock deleted file mode 100644 index 7b2456e16..000000000 --- a/09_hw_debug_JTAG/Cargo.lock +++ /dev/null @@ -1,33 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "register", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/09_hw_debug_JTAG/Cargo.toml b/09_hw_debug_JTAG/Cargo.toml deleted file mode 100644 index b8906da1f..000000000 --- a/09_hw_debug_JTAG/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Optional dependencies -register = { version = "1.x.x", optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/09_hw_debug_JTAG/Makefile b/09_hw_debug_JTAG/Makefile deleted file mode 100644 index 5f49b1af5..000000000 --- a/09_hw_debug_JTAG/Makefile +++ /dev/null @@ -1,146 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot -DOCKER_ARG_DEV = --privileged -v /dev:/dev -DOCKER_ARG_NET = --network host - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) - DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) - DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -else - DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot jtagboot openocd gdb gdb-opt0 clippy \ - clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -endif - -chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -jtagboot: - @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) - -openocd: - @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) - -define gen_gdb - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC) $1" $(RUSTC_CMD) - @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) -endef - -gdb: - $(call gen_gdb,-C debuginfo=2) - -gdb-opt0: - $(call gen_gdb,-C debuginfo=2 -C opt-level=0) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/09_hw_debug_JTAG/README.md b/09_hw_debug_JTAG/README.md deleted file mode 100644 index 93b66a66f..000000000 --- a/09_hw_debug_JTAG/README.md +++ /dev/null @@ -1,382 +0,0 @@ -# Tutorial 09 - Hardware Debugging using JTAG - -## tl;dr - -In the exact order as listed: - -1. `make jtagboot` and keep terminal open. -2. Connect USB serial device. -3. Connect `JTAG` debugger USB device. -4. In new terminal, `make openocd` and keep terminal open. -5. In new terminal, `make gdb` or make `make gdb-opt0`. - -![Demo](../doc/09_demo.gif) - -## Table of Contents - -- [Introduction](#introduction) -- [Outline](#outline) -- [Software Setup](#software-setup) -- [Hardware Setup](#hardware-setup) - * [Wiring](#wiring) -- [Getting ready to connect](#getting-ready-to-connect) -- [OpenOCD](#openocd) -- [GDB](#gdb) - * [Remarks](#remarks) - + [Optimization](#optimization) - + [GDB control](#gdb-control) -- [Notes on USB connection constraints](#notes-on-usb-connection-constraints) -- [Additional resources](#additional-resources) -- [Acknowledgments](#acknowledgments) -- [Diff to previous](#diff-to-previous) - -## Introduction - -In the upcoming tutorials, we are going to touch sensitive areas of the RPi's SoC that can make our -debugging life very hard. For example, changing the processor's `Privilege Level` or introducing -`Virtual Memory`. - -A hardware based debugger can sometimes be the last resort when searching for a tricky bug. -Especially for debugging intricate, architecture-specific HW issues, it will be handy, because in -this area `QEMU` sometimes can not help, since it abstracts certain features of the HW and doesn't -simulate down to the very last bit. - -So lets introduce `JTAG` debugging. Once set up, it will allow us to single-step through our kernel -on the real HW. How cool is that?! - -## Outline - -From kernel perspective, this tutorial is the same as the previous one. We are just wrapping -infrastructure for JTAG debugging around it. - -## Software Setup - -We need to add another line to the `config.txt` file from the SD Card: - -```toml -init_uart_clock=48000000 -enable_jtag_gpio=1 -``` - -## Hardware Setup - -Unlike microcontroller boards like the `STM32F3DISCOVERY`, which is used in our WG's [Embedded Rust -Book], the Raspberry Pi does not have an embedded debugger on its board. Hence, you need to buy one. - -For this tutorial, we will use the [ARM-USB-TINY-H] from OLIMEX. It has a standard [ARM JTAG 20 -connector]. Unfortunately, the RPi does not, so we have to connect it via jumper wires. - -[Embedded Rust Book]: https://rust-embedded.github.io/book/start/hardware.html -[ARM-USB-TINY-H]: https://www.olimex.com/Products/ARM/JTAG/ARM-USB-TINY-H -[ARM JTAG 20 connector]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0499dj/BEHEIHCE.html - -### Wiring - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GPIO #NameJTAG #NoteDiagram
VTREF1to 3.3V
GND4to GND
22TRST3
26TDI5
27TMS7
25TCK9
23RTCK11
24TDO13
- -

- -## Getting ready to connect - -Upon booting, thanks to the changes we made to `config.txt`, the RPi's firmware will configure the -respective GPIO pins for `JTAG` functionality. - -What is left to do now is to pause the execution of the RPi and then connect -over `JTAG`. Therefore, we add a new `Makefile` target, `make jtagboot`, which -uses the `chainboot` approach to load a tiny helper binary onto the RPi that -just parks the executing core into a waiting state. - -The helper binary is maintained separately in this repository's [X1_JTAG_boot] folder, and is a -modified version of the kernel we used in our tutorials so far. - -[X1_JTAG_boot]: ../X1_JTAG_boot - -```console -$ make jtagboot -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 3 - -[ML] Requesting binary -[MP] ⏩ Pushing 8 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 -[ML] Loaded! Executing the payload now - -[ 0.372110] Parking CPU core. Please connect over JTAG now. -``` - -It is important to keep the USB serial connected and the terminal with the `jtagboot` open and -running. When we load the actual kernel later, `UART` output will appear here. - -## OpenOCD - -Next, we need to launch the [Open On-Chip Debugger], aka `OpenOCD` to actually connect the `JTAG`. - -[Open On-Chip Debugger]: http://openocd.org - -As always, our tutorials try to be as painless as possible regarding dev-tools, which is why we have -packaged everything into the [dedicated Docker container] that is already used for chainbooting and -`QEMU`. - -[dedicated Docker container]: ../docker/rustembedded-osdev-utils - -Connect the Olimex USB JTAG debugger, open a new terminal and in the same folder, type `make -openocd` (in that order!). You will see some initial output: - -```console -$ make openocd -[...] -Open On-Chip Debugger 0.10.0 -[...] -Info : Listening on port 6666 for tcl connections -Info : Listening on port 4444 for telnet connections -Info : clock speed 1000 kHz -Info : JTAG tap: rpi3.tap tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4) -Info : rpi3.core0: hardware has 6 breakpoints, 4 watchpoints -Info : rpi3.core1: hardware has 6 breakpoints, 4 watchpoints -Info : rpi3.core2: hardware has 6 breakpoints, 4 watchpoints -Info : rpi3.core3: hardware has 6 breakpoints, 4 watchpoints -Info : Listening on port 3333 for gdb connections -Info : Listening on port 3334 for gdb connections -Info : Listening on port 3335 for gdb connections -Info : Listening on port 3336 for gdb connections -``` - -`OpenOCD` has detected the four cores of the RPi, and opened four network ports to which `gdb` can -now connect to debug the respective core. - -## GDB - -Finally, we need an `AArch64`-capable version of `gdb`. You guessed right, it's already packaged in -the osdev container. It can be launched via `make gdb`. - -This Makefile target actually does a little more. It builds a special version of our kernel with -debug information included. This enables `gdb` to show the `Rust` source code line we are currently -debugging. It also launches `gdb` such that it already loads this debug build (`kernel_for_jtag`). - -We can now use the `gdb` commandline to - 1. Set breakpoints in our kernel - 2. Load the kernel via JTAG into memory (remember that currently, the RPi is still executing the - minimal JTAG boot binary). - 3. Manipulate the program counter of the RPi to start execution at our kernel's entry point. - 4. Single-step through its execution. - -```console -$ make gdb -[...] ->>> target remote :3333 # Connect to OpenOCD, core0 ->>> load # Load the kernel into the RPi's DRAM over JTAG. -Loading section .text, size 0x2340 lma 0x80000 -Loading section .rodata, size 0xc2d lma 0x82340 -Loading section .data, size 0x20 lma 0x82f70 -Start address 0x80000, load size 12173 -Transfer rate: 65 KB/sec, 4057 bytes/write. ->>> set $pc = 0x80000 # Set RPI's program counter to the start of the - # kernel binary. ->>> break main.rs:70 -Breakpoint 1 at 0x80108: file src/main.rs, line 153. ->>> cont ->>> step # Single-step through the kernel ->>> step ->>> ... -``` - -### Remarks - -#### Optimization - -When debugging an OS binary, you have to make a trade-off between the granularity at which you can -step through your Rust source-code and the optimization level of the generated binary. The `make` -and `make gdb` targets produce a `--release` binary, which includes an optimization level of three -(`-opt-level=3`). However, in this case, the compiler will inline very aggressively and pack -together reads and writes where possible. As a result, it will not always be possible to hit -breakpoints exactly where you want to regarding the line of source code file. - -For this reason, the Makefile also provides the `make gdb-opt0` target, which uses `-opt-level=0`. -Hence, it will allow you to have finer debugging granularity. However, please keep in mind that when -debugging code that closely deals with HW, a compiler optimization that squashes reads or writes to -volatile registers can make all the difference in execution. FYI, the demo gif above has been -recorded with `gdb-opt0`. - -#### GDB control - -At some point, you may reach delay loops or code that waits on user input from the serial. Here, -single stepping might not be feasible or work anymore. You can jump over these roadblocks by setting -other breakpoints beyond these areas, and reach them using the `cont` command. - -Pressing `ctrl+c` in `gdb` will stop execution of the RPi again in case you continued it without -further breakpoints. - -## Notes on USB connection constraints - -If you followed the tutorial from top to bottom, everything should be fine regarding USB -connections. - -Still, please note that in its current form, our `Makefile` makes implicit assumptions about the -naming of the connected USB devices. It expects `/dev/ttyUSB0` to be the `UART` device. - -Hence, please ensure the following order of connecting the devices to your box: - 1. Connect the USB serial. - 2. Afterwards, the Olimex debugger. - -This way, Linux enumerates the devices accordingly. This has to be done only once. It is fine to -disconnect and connect the serial multiple times, e.g. for kicking off different `make jtagboot` -runs, while keeping the debugger connected. - -## Additional resources - -- https://metebalci.com/blog/bare-metal-raspberry-pi-3b-jtag -- https://www.suse.com/c/debugging-raspberry-pi-3-with-jtag - -## Acknowledgments - -Thanks to [@naotaco](https://github.com/naotaco) for laying the groundwork for this tutorial. - -## Diff to previous -```diff - -diff -uNr 08_timestamps/Makefile 09_hw_debug_JTAG/Makefile ---- 08_timestamps/Makefile -+++ 09_hw_debug_JTAG/Makefile -@@ -20,6 +20,8 @@ - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm -+ OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg -+ JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 - else ifeq ($(BSP),rpi4) -@@ -30,6 +32,8 @@ - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm -+ OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg -+ JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 - endif -@@ -58,9 +62,12 @@ - DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial - DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t - DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -+DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot - DOCKER_ARG_DEV = --privileged -v /dev:/dev -+DOCKER_ARG_NET = --network host - - DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -+DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) - DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - - # Dockerize commands that require USB device passthrough only on Linux -@@ -68,12 +75,17 @@ - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) -+ DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) -+ DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -+else -+ DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# - endif - - EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) - EXEC_MINIPUSH = ruby ../utils/minipush.rb - --.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot clippy clean readelf objdump nm check -+.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot jtagboot openocd gdb gdb-opt0 clippy \ -+ clean readelf objdump nm check - - all: $(KERNEL_BIN) - -@@ -97,6 +109,23 @@ - chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -+jtagboot: -+ @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) -+ -+openocd: -+ @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) -+ -+define gen_gdb -+ RUSTFLAGS="$(RUSTFLAGS_PEDANTIC) $1" $(RUSTC_CMD) -+ @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) -+endef -+ -+gdb: -+ $(call gen_gdb,-C debuginfo=2) -+ -+gdb-opt0: -+ $(call gen_gdb,-C debuginfo=2 -C opt-level=0) -+ - clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -``` diff --git a/09_hw_debug_JTAG/build.rs b/09_hw_debug_JTAG/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/09_hw_debug_JTAG/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/09_hw_debug_JTAG/src/_arch/aarch64/cpu.rs b/09_hw_debug_JTAG/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 3f502ee02..000000000 --- a/09_hw_debug_JTAG/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - use crate::runtime_init; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); - runtime_init::runtime_init() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} diff --git a/09_hw_debug_JTAG/src/_arch/aarch64/cpu/smp.rs b/09_hw_debug_JTAG/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/09_hw_debug_JTAG/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/09_hw_debug_JTAG/src/_arch/aarch64/time.rs b/09_hw_debug_JTAG/src/_arch/aarch64/time.rs deleted file mode 100644 index af98ddd01..000000000 --- a/09_hw_debug_JTAG/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) - } - - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; - - Duration::from_nanos(current_count / frq) - } - - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } - - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get() as u64; - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; - } - - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); - - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); - - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} - - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); - } -} diff --git a/09_hw_debug_JTAG/src/bsp.rs b/09_hw_debug_JTAG/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/09_hw_debug_JTAG/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/09_hw_debug_JTAG/src/bsp/device_driver.rs b/09_hw_debug_JTAG/src/bsp/device_driver.rs deleted file mode 100644 index ce7396f22..000000000 --- a/09_hw_debug_JTAG/src/bsp/device_driver.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/09_hw_debug_JTAG/src/bsp/device_driver/bcm.rs b/09_hw_debug_JTAG/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 59071d5d8..000000000 --- a/09_hw_debug_JTAG/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/09_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/09_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index 15bd3b78b..000000000 --- a/09_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; - use core::time::Duration; - - // The Linux 2837 GPIO driver waits 1 µs between the steps. - const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/09_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/09_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index e39bc7cdb..000000000 --- a/09_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,323 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => _reserved3), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Read one character. - let mut ret = inner.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - inner.chars_read += 1; - - ret - }) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} diff --git a/09_hw_debug_JTAG/src/bsp/device_driver/common.rs b/09_hw_debug_JTAG/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/09_hw_debug_JTAG/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/09_hw_debug_JTAG/src/bsp/raspberrypi.rs b/09_hw_debug_JTAG/src/bsp/raspberrypi.rs deleted file mode 100644 index 10888d37f..000000000 --- a/09_hw_debug_JTAG/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/09_hw_debug_JTAG/src/bsp/raspberrypi/console.rs b/09_hw_debug_JTAG/src/bsp/raspberrypi/console.rs deleted file mode 100644 index d1b60dd82..000000000 --- a/09_hw_debug_JTAG/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} diff --git a/09_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs b/09_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/09_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/09_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs b/09_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index fe24dd71b..000000000 --- a/09_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/09_hw_debug_JTAG/src/bsp/raspberrypi/link.ld b/09_hw_debug_JTAG/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/09_hw_debug_JTAG/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/09_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs b/09_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index fae051257..000000000 --- a/09_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/09_hw_debug_JTAG/src/console.rs b/09_hw_debug_JTAG/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/09_hw_debug_JTAG/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/09_hw_debug_JTAG/src/cpu.rs b/09_hw_debug_JTAG/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/09_hw_debug_JTAG/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/09_hw_debug_JTAG/src/cpu/smp.rs b/09_hw_debug_JTAG/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/09_hw_debug_JTAG/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/09_hw_debug_JTAG/src/driver.rs b/09_hw_debug_JTAG/src/driver.rs deleted file mode 100644 index e2875b876..000000000 --- a/09_hw_debug_JTAG/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/09_hw_debug_JTAG/src/main.rs b/09_hw_debug_JTAG/src/main.rs deleted file mode 100644 index 2c9f1fb7f..000000000 --- a/09_hw_debug_JTAG/src/main.rs +++ /dev/null @@ -1,177 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![feature(const_fn_fn_ptr_basics)] -#![feature(format_args_nl)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod driver; -mod memory; -mod panic_wait; -mod print; -mod runtime_init; -mod synchronization; -mod time; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order. -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; - - info!("Booting on: {}", bsp::board_name()); - - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() - ); - - info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } - - // Test a failing timer case. - time::time_manager().spin_for(Duration::from_nanos(1)); - - loop { - info!("Spinning for 1 second"); - time::time_manager().spin_for(Duration::from_secs(1)); - } -} diff --git a/09_hw_debug_JTAG/src/memory.rs b/09_hw_debug_JTAG/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/09_hw_debug_JTAG/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/09_hw_debug_JTAG/src/panic_wait.rs b/09_hw_debug_JTAG/src/panic_wait.rs deleted file mode 100644 index 1386e1e23..000000000 --- a/09_hw_debug_JTAG/src/panic_wait.rs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/09_hw_debug_JTAG/src/print.rs b/09_hw_debug_JTAG/src/print.rs deleted file mode 100644 index 8b6f3f988..000000000 --- a/09_hw_debug_JTAG/src/print.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} - -/// Prints an info, with a newline. -#[macro_export] -macro_rules! info { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} - -/// Prints a warning, with a newline. -#[macro_export] -macro_rules! warn { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} diff --git a/09_hw_debug_JTAG/src/runtime_init.rs b/09_hw_debug_JTAG/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/09_hw_debug_JTAG/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/09_hw_debug_JTAG/src/synchronization.rs b/09_hw_debug_JTAG/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/09_hw_debug_JTAG/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/09_hw_debug_JTAG/src/time.rs b/09_hw_debug_JTAG/src/time.rs deleted file mode 100644 index cd3ceec33..000000000 --- a/09_hw_debug_JTAG/src/time.rs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; -pub use arch_time::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); - } -} diff --git a/09_privilege_level/.vscode/settings.json b/09_privilege_level/.vscode/settings.json new file mode 100644 index 000000000..bfa278e9a --- /dev/null +++ b/09_privilege_level/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/09_privilege_level/Cargo.lock b/09_privilege_level/Cargo.lock new file mode 100644 index 000000000..12b210428 --- /dev/null +++ b/09_privilege_level/Cargo.lock @@ -0,0 +1,26 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.9.0" +dependencies = [ + "aarch64-cpu", + "tock-registers", +] + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/09_privilege_level/Cargo.toml b/09_privilege_level/Cargo.toml new file mode 100644 index 000000000..480508b53 --- /dev/null +++ b/09_privilege_level/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "mingo" +version = "0.9.0" +authors = ["Andre Richter "] +edition = "2021" + +[profile.release] +lto = true + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] + +[[bin]] +name = "kernel" +path = "src/main.rs" + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/09_privilege_level/Makefile b/09_privilege_level/Makefile new file mode 100644 index 000000000..9549f0920 --- /dev/null +++ b/09_privilege_level/Makefile @@ -0,0 +1,279 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/09_privilege_level/README.CN.md b/09_privilege_level/README.CN.md new file mode 100644 index 000000000..80773a690 --- /dev/null +++ b/09_privilege_level/README.CN.md @@ -0,0 +1,182 @@ +# 教程 09 - 特权级别 + +## tl;dr + +- 在早期引导代码中,我们从`Hypervisor`特权级别(AArch64中的`EL2`)过渡到`Kernel` (`EL1`)特权级别。 + +## 目录 + +- [介绍](#介绍) +- [本教程的范围](#本教程的范围) +- [在入口点检查EL2](#在入口点检查EL2) +- [过渡准备](#过渡准备) +- [从未发生的异常中返回](#从未发生的异常中返回) +- [测试](#测试) +- [相比之前的变化(diff)](#相比之前的变化(diff)) + +## 介绍 + +应用级别的CPU具有所谓的`privilege levels`,它们具有不同的目的: + +| Typically used for | AArch64 | RISC-V | x86 | +| ------------- | ------------- | ------------- | ------------- | +| Userspace applications | EL0 | U/VU | Ring 3 | +| OS Kernel | EL1 | S/VS | Ring 0 | +| Hypervisor | EL2 | HS | Ring -1 | +| Low-Level Firmware | EL3 | M | | + +在AArch64中,`EL`代表`Exception Level`(异常级别)。如果您想获取有关其他体系结构的更多信息,请查看以下链接: +- [x86 privilege rings](https://en.wikipedia.org/wiki/Protection_ring). +- [RISC-V privilege modes](https://content.riscv.org/wp-content/uploads/2017/12/Tue0942-riscv-hypervisor-waterman.pdf). + +在继续之前,我强烈建议您先浏览一下[Programmer’s Guide for ARMv8-A]`的第3章`。它提供了关于该主题的简明概述。 + +[Programmer’s Guide for ARMv8-A]: http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf + +## 本教程的范围 + +默认情况下,树莓派将始终在`EL2`中开始执行。由于我们正在编写一个传统的`Kernel`,我们需要过渡到更合适的`EL1`。 + +## 在入口点检查EL2 + +首先,我们需要确保我们实际上是在`EL2`中执行,然后才能调用相应的代码过渡到`EL1`。 +因此,我们在`boot.s`的顶部添加了一个新的检查,如果CPU核心不在`EL2`中,则将其停止。 + +``` +// Only proceed if the core executes in EL2. Park it otherwise. +mrs x0, CurrentEL +cmp x0, {CONST_CURRENTEL_EL2} +b.ne .L_parking_loop +``` + +接下来,在`boot.rs`中继续准备从`EL2`到`EL1`的过渡,通过调用`prepare_el2_to_el1_transition()`函数。 + +```rust +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} +``` + +## 过渡准备 + +由于`EL2`比`EL1`更具特权,它可以控制各种处理器功能,并允许或禁止`EL1`代码使用它们。 +其中一个例子是访问计时器和计数器寄存器。我们已经在[tutorial 07](../07_timestamps/)中使用了它们,所以当然我们希望保留它们。 +因此,我们在[Counter-timer Hypervisor Control register]中设置相应的标志,并将虚拟偏移量设置为零,以获取真实的物理值。 + +[Counter-timer Hypervisor Control register]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/cnthctl_el2.rs.html + +```rust +// Enable timer counter registers for EL1. +CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + +// No offset for reading the counters. +CNTVOFF_EL2.set(0); +``` + +接下来,我们配置[Hypervisor Configuration Register],使`EL1`在`AArch64`模式下运行,而不是在`AArch32`模式下运行,这也是可能的。 + +[Hypervisor Configuration Register]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/hcr_el2.rs.html + +```rust +// Set EL1 execution state to AArch64. +HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); +``` + +## 从未发生的异常中返回 + +实际上,从较高的EL过渡到较低的EL只有一种方式,即通过执行[ERET]指令。 + +[ERET]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/asm.rs.html#92-101 + +在这个指令中,它将会将[Saved Program Status Register - EL2]的内容复制到`Current Program Status Register - EL1`,并跳转到存储在[Exception Link Register - EL2]。 + +这基本上是在发生异常时所发生的相反过程。您将在即将发布的教程中了解更多相关内容。 + +[Saved Program Status Register - EL2]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/spsr_el2.rs.html +[Exception Link Register - EL2]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/elr_el2.rs.html + +```rust +// Set up a simulated exception return. +// +// First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a +// stack pointer. +SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, +); + +// Second, let the link register point to kernel_init(). +ELR_EL2.set(crate::kernel_init as *const () as u64); + +// Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there +// are no plans to ever return to EL2, just re-use the same stack. +SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +``` + +正如您所看到的,我们将`ELR_EL2`的值设置为之前直接从入口点调用的`kernel_init()`函数的地址。最后,我们设置了`SP_EL1`的堆栈指针。 + +您可能已经注意到,堆栈的地址作为函数参数进行了传递。正如您可能记得的,在`boot.s`的`_start()`函数中, +我们已经为`EL2`设置了堆栈。由于没有计划返回到`EL2`,我们可以直接重用相同的堆栈作为`EL1`的堆栈, +因此使用函数参数将其地址传递。 + +最后,在`_start_rust()`函数中调用了`ERET`指令。 + +```rust +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} +``` + +## 测试 + +在`main.rs`中,我们打印`current privilege level`,并额外检查`SPSR_EL2`中的掩码位是否传递到了`EL1`: + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 14 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.162546] mingo version 0.9.0 +[ 0.162745] Booting on: Raspberry Pi 3 +[ 0.163201] Current privilege level: EL1 +[ 0.163677] Exception handling state: +[ 0.164122] Debug: Masked +[ 0.164511] SError: Masked +[ 0.164901] IRQ: Masked +[ 0.165291] FIQ: Masked +[ 0.165681] Architectural timer resolution: 52 ns +[ 0.166255] Drivers loaded: +[ 0.166592] 1. BCM PL011 UART +[ 0.167014] 2. BCM GPIO +[ 0.167371] Timer test, spinning for 1 second +[ 1.167904] Echoing input now +``` + +## 相比之前的变化(diff) +请检查[英文版本](README.md#diff-to-previous),这是最新的。 diff --git a/09_privilege_level/README.md b/09_privilege_level/README.md new file mode 100644 index 000000000..ca2b920f1 --- /dev/null +++ b/09_privilege_level/README.md @@ -0,0 +1,574 @@ +# Tutorial 09 - Privilege Level + +## tl;dr + +- In early boot code, we transition from the `Hypervisor` privilege level (`EL2` in AArch64) to the + `Kernel` (`EL1`) privilege level. + +## Table of Contents + +- [Introduction](#introduction) +- [Scope of this tutorial](#scope-of-this-tutorial) +- [Checking for EL2 in the entrypoint](#checking-for-el2-in-the-entrypoint) +- [Transition preparation](#transition-preparation) +- [Returning from an exception that never happened](#returning-from-an-exception-that-never-happened) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +Application-grade CPUs have so-called `privilege levels`, which have different purposes: + +| Typically used for | AArch64 | RISC-V | x86 | +| ------------- | ------------- | ------------- | ------------- | +| Userspace applications | EL0 | U/VU | Ring 3 | +| OS Kernel | EL1 | S/VS | Ring 0 | +| Hypervisor | EL2 | HS | Ring -1 | +| Low-Level Firmware | EL3 | M | | + +`EL` in AArch64 stands for `Exception Level`. If you want more information regarding the other +architectures, please have a look at the following links: +- [x86 privilege rings](https://en.wikipedia.org/wiki/Protection_ring). +- [RISC-V privilege modes](https://content.riscv.org/wp-content/uploads/2017/12/Tue0942-riscv-hypervisor-waterman.pdf). + +At this point, I strongly recommend that you glimpse over `Chapter 3` of the [Programmer’s Guide for +ARMv8-A] before you continue. It gives a concise overview about the topic. + +[Programmer’s Guide for ARMv8-A]: http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf + +## Scope of this tutorial + +By default, the Raspberry will always start executing in `EL2`. Since we are writing a traditional +`Kernel`, we have to transition into the more appropriate `EL1`. + +## Checking for EL2 in the entrypoint + +First of all, we need to ensure that we actually execute in `EL2` before we can call respective code +to transition to `EL1`. Therefore, we add a new checkt to the top of `boot.s`, which parks the CPU +core should it not be in `EL2`. + +``` +// Only proceed if the core executes in EL2. Park it otherwise. +mrs x0, CurrentEL +cmp x0, {CONST_CURRENTEL_EL2} +b.ne .L_parking_loop +``` + +Afterwards, we continue with preparing the `EL2` -> `EL1` transition by calling +`prepare_el2_to_el1_transition()` in `boot.rs`: + +```rust +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} +``` + +## Transition preparation + +Since `EL2` is more privileged than `EL1`, it has control over various processor features and can +allow or disallow `EL1` code to use them. One such example is access to timer and counter registers. +We are already using them since [tutorial 07](../07_timestamps/), so of course we want to keep them. +Therefore we set the respective flags in the [Counter-timer Hypervisor Control register] and +additionally set the virtual offset to zero so that we get the real physical value everytime: + +[Counter-timer Hypervisor Control register]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/cnthctl_el2.rs.html + +```rust +// Enable timer counter registers for EL1. +CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + +// No offset for reading the counters. +CNTVOFF_EL2.set(0); +``` + +Next, we configure the [Hypervisor Configuration Register] such that `EL1` runs in `AArch64` mode, +and not in `AArch32`, which would also be possible. + +[Hypervisor Configuration Register]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/hcr_el2.rs.html + +```rust +// Set EL1 execution state to AArch64. +HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); +``` + +## Returning from an exception that never happened + +There is actually only one way to transition from a higher EL to a lower EL, which is by way of +executing the [ERET] instruction. + +[ERET]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/asm.rs.html#92-101 + +This instruction will copy the contents of the [Saved Program Status Register - EL2] to `Current +Program Status Register - EL1` and jump to the instruction address that is stored in the [Exception +Link Register - EL2]. + +This is basically the reverse of what is happening when an exception is taken. You'll learn about +that in an upcoming tutorial. + +[Saved Program Status Register - EL2]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/spsr_el2.rs.html +[Exception Link Register - EL2]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/elr_el2.rs.html + +```rust +// Set up a simulated exception return. +// +// First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a +// stack pointer. +SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, +); + +// Second, let the link register point to kernel_init(). +ELR_EL2.set(crate::kernel_init as *const () as u64); + +// Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there +// are no plans to ever return to EL2, just re-use the same stack. +SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +``` + +As you can see, we are populating `ELR_EL2` with the address of the `kernel_init()` function that we +earlier used to call directly from the entrypoint. Finally, we set the stack pointer for `SP_EL1`. + +You might have noticed that the stack's address was supplied as a function argument. As you might +remember, in `_start()` in `boot.s`, we are already setting up the stack for `EL2`. Since there +are no plans to ever return to `EL2`, we can just re-use the same stack for `EL1`, so its address is +forwarded using function arguments. + +Lastly, back in `_start_rust()` a call to `ERET` is made: + +```rust +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} +``` + +## Test it + +In `main.rs`, we print the `current privilege level` and additionally inspect if the mask bits in +`SPSR_EL2` made it to `EL1` as well: + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 14 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.162546] mingo version 0.9.0 +[ 0.162745] Booting on: Raspberry Pi 3 +[ 0.163201] Current privilege level: EL1 +[ 0.163677] Exception handling state: +[ 0.164122] Debug: Masked +[ 0.164511] SError: Masked +[ 0.164901] IRQ: Masked +[ 0.165291] FIQ: Masked +[ 0.165681] Architectural timer resolution: 52 ns +[ 0.166255] Drivers loaded: +[ 0.166592] 1. BCM PL011 UART +[ 0.167014] 2. BCM GPIO +[ 0.167371] Timer test, spinning for 1 second +[ 1.167904] Echoing input now +``` + +## Diff to previous +```diff + +diff -uNr 08_hw_debug_JTAG/Cargo.toml 09_privilege_level/Cargo.toml +--- 08_hw_debug_JTAG/Cargo.toml ++++ 09_privilege_level/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.8.0" ++version = "0.9.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs 09_privilege_level/src/_arch/aarch64/cpu/boot.rs +--- 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs ++++ 09_privilege_level/src/_arch/aarch64/cpu/boot.rs +@@ -11,22 +11,73 @@ + //! + //! crate::cpu::boot::arch_boot + ++use aarch64_cpu::{asm, registers::*}; + use core::arch::global_asm; ++use tock_registers::interfaces::Writeable; + + // Assembly counterpart to this file. + global_asm!( + include_str!("boot.s"), ++ CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 + ); + + //-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Prepares the transition from EL2 to EL1. ++/// ++/// # Safety ++/// ++/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. ++/// - The HW state of EL1 must be prepared in a sound way. ++#[inline(always)] ++unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { ++ // Enable timer counter registers for EL1. ++ CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); ++ ++ // No offset for reading the counters. ++ CNTVOFF_EL2.set(0); ++ ++ // Set EL1 execution state to AArch64. ++ HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); ++ ++ // Set up a simulated exception return. ++ // ++ // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a ++ // stack pointer. ++ SPSR_EL2.write( ++ SPSR_EL2::D::Masked ++ + SPSR_EL2::A::Masked ++ + SPSR_EL2::I::Masked ++ + SPSR_EL2::F::Masked ++ + SPSR_EL2::M::EL1h, ++ ); ++ ++ // Second, let the link register point to kernel_init(). ++ ELR_EL2.set(crate::kernel_init as *const () as u64); ++ ++ // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there ++ // are no plans to ever return to EL2, just re-use the same stack. ++ SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); ++} ++ ++//-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- + + /// The Rust entry of the `kernel` binary. + /// + /// The function is called from the assembly `_start` function. ++/// ++/// # Safety ++/// ++/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. + #[no_mangle] +-pub unsafe fn _start_rust() -> ! { +- crate::kernel_init() ++pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { ++ prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); ++ ++ // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. ++ asm::eret() + } + +diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s 09_privilege_level/src/_arch/aarch64/cpu/boot.s +--- 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s ++++ 09_privilege_level/src/_arch/aarch64/cpu/boot.s +@@ -27,11 +27,16 @@ + // fn _start() + //------------------------------------------------------------------------------ + _start: ++ // Only proceed if the core executes in EL2. Park it otherwise. ++ mrs x0, CurrentEL ++ cmp x0, {CONST_CURRENTEL_EL2} ++ b.ne .L_parking_loop ++ + // Only proceed on the boot core. Park it otherwise. +- mrs x0, MPIDR_EL1 +- and x0, x0, {CONST_CORE_ID_MASK} +- ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs +- cmp x0, x1 ++ mrs x1, MPIDR_EL1 ++ and x1, x1, {CONST_CORE_ID_MASK} ++ ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs ++ cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. +@@ -48,7 +53,7 @@ + + // Prepare the jump to Rust code. + .L_prepare_rust: +- // Set the stack pointer. ++ // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + +@@ -60,7 +65,7 @@ + b.eq .L_parking_loop + str w2, [x1] + +- // Jump to Rust code. ++ // Jump to Rust code. x0 holds the function argument provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). + +diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/exception/asynchronous.rs 09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs +--- 08_hw_debug_JTAG/src/_arch/aarch64/exception/asynchronous.rs ++++ 09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs +@@ -0,0 +1,82 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Architectural asynchronous exception handling. ++//! ++//! # Orientation ++//! ++//! Since arch modules are imported into generic modules using the path attribute, the path of this ++//! file is: ++//! ++//! crate::exception::asynchronous::arch_asynchronous ++ ++use aarch64_cpu::registers::*; ++use tock_registers::interfaces::Readable; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++trait DaifField { ++ fn daif_field() -> tock_registers::fields::Field; ++} ++ ++struct Debug; ++struct SError; ++struct IRQ; ++struct FIQ; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl DaifField for Debug { ++ fn daif_field() -> tock_registers::fields::Field { ++ DAIF::D ++ } ++} ++ ++impl DaifField for SError { ++ fn daif_field() -> tock_registers::fields::Field { ++ DAIF::A ++ } ++} ++ ++impl DaifField for IRQ { ++ fn daif_field() -> tock_registers::fields::Field { ++ DAIF::I ++ } ++} ++ ++impl DaifField for FIQ { ++ fn daif_field() -> tock_registers::fields::Field { ++ DAIF::F ++ } ++} ++ ++fn is_masked() -> bool ++where ++ T: DaifField, ++{ ++ DAIF.is_set(T::daif_field()) ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Print the AArch64 exceptions status. ++#[rustfmt::skip] ++pub fn print_state() { ++ use crate::info; ++ ++ let to_mask_str = |x| -> _ { ++ if x { "Masked" } else { "Unmasked" } ++ }; ++ ++ info!(" Debug: {}", to_mask_str(is_masked::())); ++ info!(" SError: {}", to_mask_str(is_masked::())); ++ info!(" IRQ: {}", to_mask_str(is_masked::())); ++ info!(" FIQ: {}", to_mask_str(is_masked::())); ++} + +diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/exception.rs 09_privilege_level/src/_arch/aarch64/exception.rs +--- 08_hw_debug_JTAG/src/_arch/aarch64/exception.rs ++++ 09_privilege_level/src/_arch/aarch64/exception.rs +@@ -0,0 +1,31 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Architectural synchronous and asynchronous exception handling. ++//! ++//! # Orientation ++//! ++//! Since arch modules are imported into generic modules using the path attribute, the path of this ++//! file is: ++//! ++//! crate::exception::arch_exception ++ ++use aarch64_cpu::registers::*; ++use tock_registers::interfaces::Readable; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++use crate::exception::PrivilegeLevel; ++ ++/// The processing element's current privilege level. ++pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { ++ let el = CurrentEL.read_as_enum(CurrentEL::EL); ++ match el { ++ Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), ++ Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), ++ Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), ++ _ => (PrivilegeLevel::Unknown, "Unknown"), ++ } ++} + +diff -uNr 08_hw_debug_JTAG/src/exception/asynchronous.rs 09_privilege_level/src/exception/asynchronous.rs +--- 08_hw_debug_JTAG/src/exception/asynchronous.rs ++++ 09_privilege_level/src/exception/asynchronous.rs +@@ -0,0 +1,14 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Asynchronous exception handling. ++ ++#[cfg(target_arch = "aarch64")] ++#[path = "../_arch/aarch64/exception/asynchronous.rs"] ++mod arch_asynchronous; ++ ++//-------------------------------------------------------------------------------------------------- ++// Architectural Public Reexports ++//-------------------------------------------------------------------------------------------------- ++pub use arch_asynchronous::print_state; + +diff -uNr 08_hw_debug_JTAG/src/exception.rs 09_privilege_level/src/exception.rs +--- 08_hw_debug_JTAG/src/exception.rs ++++ 09_privilege_level/src/exception.rs +@@ -0,0 +1,30 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Synchronous and asynchronous exception handling. ++ ++#[cfg(target_arch = "aarch64")] ++#[path = "_arch/aarch64/exception.rs"] ++mod arch_exception; ++ ++pub mod asynchronous; ++ ++//-------------------------------------------------------------------------------------------------- ++// Architectural Public Reexports ++//-------------------------------------------------------------------------------------------------- ++pub use arch_exception::current_privilege_level; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Kernel privilege levels. ++#[allow(missing_docs)] ++#[derive(Eq, PartialEq)] ++pub enum PrivilegeLevel { ++ User, ++ Kernel, ++ Hypervisor, ++ Unknown, ++} + +diff -uNr 08_hw_debug_JTAG/src/main.rs 09_privilege_level/src/main.rs +--- 08_hw_debug_JTAG/src/main.rs ++++ 09_privilege_level/src/main.rs +@@ -121,6 +121,7 @@ + mod console; + mod cpu; + mod driver; ++mod exception; + mod panic_wait; + mod print; + mod synchronization; +@@ -148,6 +149,7 @@ + + /// The main function running after the early init. + fn kernel_main() -> ! { ++ use console::console; + use core::time::Duration; + + info!( +@@ -157,6 +159,12 @@ + ); + info!("Booting on: {}", bsp::board_name()); + ++ let (_, privilege_level) = exception::current_privilege_level(); ++ info!("Current privilege level: {}", privilege_level); ++ ++ info!("Exception handling state:"); ++ exception::asynchronous::print_state(); ++ + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() +@@ -165,11 +173,15 @@ + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + +- // Test a failing timer case. +- time::time_manager().spin_for(Duration::from_nanos(1)); ++ info!("Timer test, spinning for 1 second"); ++ time::time_manager().spin_for(Duration::from_secs(1)); ++ ++ info!("Echoing input now"); + ++ // Discard any spurious received characters before going into echo mode. ++ console().clear_rx(); + loop { +- info!("Spinning for 1 second"); +- time::time_manager().spin_for(Duration::from_secs(1)); ++ let c = console().read_char(); ++ console().write_char(c); + } + } + +diff -uNr 08_hw_debug_JTAG/tests/boot_test_string.rb 09_privilege_level/tests/boot_test_string.rb +--- 08_hw_debug_JTAG/tests/boot_test_string.rb ++++ 09_privilege_level/tests/boot_test_string.rb +@@ -1,3 +1,3 @@ + # frozen_string_literal: true + +-EXPECTED_PRINT = 'Spinning for 1 second' ++EXPECTED_PRINT = 'Echoing input now' + +``` diff --git a/09_privilege_level/build.rs b/09_privilege_level/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/09_privilege_level/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/09_privilege_level/src/_arch/aarch64/cpu.rs b/09_privilege_level/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..602c9789c --- /dev/null +++ b/09_privilege_level/src/_arch/aarch64/cpu.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff --git a/09_privilege_level/src/_arch/aarch64/cpu/boot.rs b/09_privilege_level/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..c80f3ebbc --- /dev/null +++ b/09_privilege_level/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(crate::kernel_init as *const () as u64); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} diff --git a/09_privilege_level/src/_arch/aarch64/cpu/boot.s b/09_privilege_level/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..f6df21236 --- /dev/null +++ b/09_privilege_level/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. x0 holds the function argument provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/09_privilege_level/src/_arch/aarch64/exception.rs b/09_privilege_level/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..1051af6aa --- /dev/null +++ b/09_privilege_level/src/_arch/aarch64/exception.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} diff --git a/09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs b/09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..65fcad25d --- /dev/null +++ b/09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/09_privilege_level/src/_arch/aarch64/time.rs b/09_privilege_level/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/09_privilege_level/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/09_privilege_level/src/bsp.rs b/09_privilege_level/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/09_privilege_level/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/09_privilege_level/src/bsp/device_driver.rs b/09_privilege_level/src/bsp/device_driver.rs new file mode 100644 index 000000000..64049a4cf --- /dev/null +++ b/09_privilege_level/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/09_privilege_level/src/bsp/device_driver/bcm.rs b/09_privilege_level/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..1c343d1d7 --- /dev/null +++ b/09_privilege_level/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..8e57dfedb --- /dev/null +++ b/09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..d92612ea8 --- /dev/null +++ b/09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff --git a/09_privilege_level/src/bsp/device_driver/common.rs b/09_privilege_level/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..dfe7d8ef3 --- /dev/null +++ b/09_privilege_level/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff --git a/09_privilege_level/src/bsp/raspberrypi.rs b/09_privilege_level/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..3ea864dc7 --- /dev/null +++ b/09_privilege_level/src/bsp/raspberrypi.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/09_privilege_level/src/bsp/raspberrypi/cpu.rs b/09_privilege_level/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/09_privilege_level/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/09_privilege_level/src/bsp/raspberrypi/driver.rs b/09_privilege_level/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..2a80ee2c5 --- /dev/null +++ b/09_privilege_level/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} diff --git a/09_privilege_level/src/bsp/raspberrypi/kernel.ld b/09_privilege_level/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..f6c188434 --- /dev/null +++ b/09_privilege_level/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/09_privilege_level/src/bsp/raspberrypi/memory.rs b/09_privilege_level/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..cdca14b8a --- /dev/null +++ b/09_privilege_level/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } +} diff --git a/09_privilege_level/src/console.rs b/09_privilege_level/src/console.rs new file mode 100644 index 000000000..a83f86fe0 --- /dev/null +++ b/09_privilege_level/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization::{self, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) +} diff --git a/09_privilege_level/src/console/null_console.rs b/09_privilege_level/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/09_privilege_level/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/09_privilege_level/src/cpu.rs b/09_privilege_level/src/cpu.rs new file mode 100644 index 000000000..67ab79c08 --- /dev/null +++ b/09_privilege_level/src/cpu.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; diff --git a/09_privilege_level/src/cpu/boot.rs b/09_privilege_level/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/09_privilege_level/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/09_privilege_level/src/driver.rs b/09_privilege_level/src/driver.rs new file mode 100644 index 000000000..050e7022f --- /dev/null +++ b/09_privilege_level/src/driver.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + info, + synchronization::{interface::Mutex, NullLock}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/09_privilege_level/src/exception.rs b/09_privilege_level/src/exception.rs new file mode 100644 index 000000000..45760391e --- /dev/null +++ b/09_privilege_level/src/exception.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::current_privilege_level; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} diff --git a/09_privilege_level/src/exception/asynchronous.rs b/09_privilege_level/src/exception/asynchronous.rs new file mode 100644 index 000000000..fd059326e --- /dev/null +++ b/09_privilege_level/src/exception/asynchronous.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::print_state; diff --git a/09_privilege_level/src/main.rs b/09_privilege_level/src/main.rs new file mode 100644 index 000000000..cc0e1dfd7 --- /dev/null +++ b/09_privilege_level/src/main.rs @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(format_args_nl)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_main] +#![no_std] + +mod bsp; +mod console; +mod cpu; +mod driver; +mod exception; +mod panic_wait; +mod print; +mod synchronization; +mod time; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order. +unsafe fn kernel_init() -> ! { + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + use console::console; + use core::time::Duration; + + info!( + "{} version {}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + info!("Booting on: {}", bsp::board_name()); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Timer test, spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); + + info!("Echoing input now"); + + // Discard any spurious received characters before going into echo mode. + console().clear_rx(); + loop { + let c = console().read_char(); + console().write_char(c); + } +} diff --git a/09_privilege_level/src/panic_wait.rs b/09_privilege_level/src/panic_wait.rs new file mode 100644 index 000000000..5776aca87 --- /dev/null +++ b/09_privilege_level/src/panic_wait.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + cpu::wait_forever() +} diff --git a/09_privilege_level/src/print.rs b/09_privilege_level/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/09_privilege_level/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/09_privilege_level/src/synchronization.rs b/09_privilege_level/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/09_privilege_level/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/09_privilege_level/src/time.rs b/09_privilege_level/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/09_privilege_level/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/09_privilege_level/tests/boot_test_string.rb b/09_privilege_level/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/09_privilege_level/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/10_privilege_level/.vscode/settings.json b/10_privilege_level/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/10_privilege_level/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/10_privilege_level/Cargo.lock b/10_privilege_level/Cargo.lock deleted file mode 100644 index 7b2456e16..000000000 --- a/10_privilege_level/Cargo.lock +++ /dev/null @@ -1,33 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "register", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/10_privilege_level/Cargo.toml b/10_privilege_level/Cargo.toml deleted file mode 100644 index b8906da1f..000000000 --- a/10_privilege_level/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Optional dependencies -register = { version = "1.x.x", optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/10_privilege_level/Makefile b/10_privilege_level/Makefile deleted file mode 100644 index 5f49b1af5..000000000 --- a/10_privilege_level/Makefile +++ /dev/null @@ -1,146 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot -DOCKER_ARG_DEV = --privileged -v /dev:/dev -DOCKER_ARG_NET = --network host - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) - DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) - DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -else - DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot jtagboot openocd gdb gdb-opt0 clippy \ - clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -endif - -chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -jtagboot: - @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) - -openocd: - @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) - -define gen_gdb - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC) $1" $(RUSTC_CMD) - @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) -endef - -gdb: - $(call gen_gdb,-C debuginfo=2) - -gdb-opt0: - $(call gen_gdb,-C debuginfo=2 -C opt-level=0) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/10_privilege_level/README.md b/10_privilege_level/README.md deleted file mode 100644 index c1e162876..000000000 --- a/10_privilege_level/README.md +++ /dev/null @@ -1,496 +0,0 @@ -# Tutorial 10 - Privilege Level - -## tl;dr - -- In early boot code, we transition from the `Hypervisor` privilege level (`EL2` in AArch64) to the - `Kernel` (`EL1`) privilege level. - -## Table of Contents - -- [Introduction](#introduction) -- [Scope of this tutorial](#scope-of-this-tutorial) -- [Checking for EL2 in the entrypoint](#checking-for-el2-in-the-entrypoint) -- [Transition preparation](#transition-preparation) -- [Returning from an exception that never happened](#returning-from-an-exception-that-never-happened) -- [Are we stackless?](#are-we-stackless) -- [Test it](#test-it) -- [Diff to previous](#diff-to-previous) - -## Introduction - -Application-grade CPUs have so-called `privilege levels`, which have different purposes: - -| Typically used for | AArch64 | RISC-V | x86 | -| ------------- | ------------- | ------------- | ------------- | -| Userspace applications | EL0 | U/VU | Ring 3 | -| OS Kernel | EL1 | S/VS | Ring 0 | -| Hypervisor | EL2 | HS | Ring -1 | -| Low-Level Firmware | EL3 | M | | - -`EL` in AArch64 stands for `Exception Level`. If you want more information regarding the other -architectures, please have a look at the following links: -- [x86 privilege rings](https://en.wikipedia.org/wiki/Protection_ring). -- [RISC-V privilege modes](https://content.riscv.org/wp-content/uploads/2017/12/Tue0942-riscv-hypervisor-waterman.pdf). - -At this point, I strongly recommend that you glimpse over `Chapter 3` of the [Programmer’s Guide for -ARMv8-A](http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf) -before you continue. It gives a concise overview about the topic. - -## Scope of this tutorial - -If you set up your SD Card exactly like mentioned in [tutorial 06], the Rpi will always start -executing in `EL2`. Since we are writing a traditional `Kernel`, we have to transition into the more -appropriate `EL1`. - -[tutorial 06]: https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/tree/master/06_drivers_gpio_uart#boot-it-from-sd-card - -## Checking for EL2 in the entrypoint - -First of all, we need to ensure that we actually execute in `EL2` before we can call respective code -to transition to `EL1`: - -```rust -pub unsafe extern "C" fn _start() -> ! { - // Expect the boot core to start in EL2. - if (bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id()) - && (CurrentEL.get() == CurrentEL::EL::EL2.value) - { - el2_to_el1_transition() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} -``` - -If this is the case, we continue with preparing the `EL2` -> `EL1` transition in -`el2_to_el1_transition()`. - -## Transition preparation - -Since `EL2` is more privileged than `EL1`, it has control over various processor features and can -allow or disallow `EL1` code to use them. One such example is access to timer and counter registers. -We are already using them since [tutorial 08](../08_timestamps/), so of course we want to keep them. -Therefore we set the respective flags in the [Counter-timer Hypervisor Control register] and -additionally set the virtual offset to zero so that we get the real physical value everytime: - -[Counter-timer Hypervisor Control register]: https://docs.rs/cortex-a/2.4.0/src/cortex_a/regs/cnthctl_el2.rs.html - -```rust -// Enable timer counter registers for EL1. -CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); - -// No offset for reading the counters. -CNTVOFF_EL2.set(0); -``` - -Next, we configure the [Hypervisor Configuration Register] such that `EL1` should actually run in -`AArch64` mode, and not in `AArch32`, which would also be possible. - -[Hypervisor Configuration Register]: https://docs.rs/cortex-a/2.4.0/src/cortex_a/regs/hcr_el2.rs.html - -```rust -// Set EL1 execution state to AArch64. -HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); -``` - -## Returning from an exception that never happened - -There is actually only one way to transition from a higher EL to a lower EL, which is by way of -executing the [ERET] instruction. - -[ERET]: https://docs.rs/cortex-a/2.4.0/src/cortex_a/asm.rs.html#49-62 - -This instruction will copy the contents of the [Saved Program Status Register - EL2] to `Current -Program Status Register - EL1` and jump to the instruction address that is stored in the [Exception -Link Register - EL2]. - -This is basically the reverse of what is happening when an exception is taken. You'll learn about it -in an upcoming tutorial. - -[Saved Program Status Register - EL2]: https://docs.rs/cortex-a/2.4.0/src/cortex_a/regs/spsr_el2.rs.html -[Exception Link Register - EL2]: https://docs.rs/cortex-a/2.4.0/src/cortex_a/regs/elr_el2.rs.html - -```rust -// Set up a simulated exception return. -// -// First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a -// stack pointer. -SPSR_EL2.write( - SPSR_EL2::D::Masked - + SPSR_EL2::A::Masked - + SPSR_EL2::I::Masked - + SPSR_EL2::F::Masked - + SPSR_EL2::M::EL1h, -); - -// Second, let the link register point to runtime_init(). -ELR_EL2.set(runtime_init::runtime_init as *const () as u64); -``` - -As you can see, we are populating `ELR_EL2` with the address of the [runtime_init()] function that -we earlier used to call directly from the entrypoint. - -Finally, we set the stack pointer for `SP_EL1` and call `ERET`: - -[runtime_init()]: src/runtime_init.rs - -```rust -// Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. -SP_EL1.set(bsp::cpu::BOOT_CORE_STACK_START); - -// Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. -asm::eret() -``` - -## Are we stackless? - -We just wrote a big inline rust function, `el2_to_el1_transition()`, that is executed in a context -where we do not have a stack yet. We should double-check the generated machine code: - -```console -$ make objdump -[...] -Disassembly of section .text: - -0000000000080000 <_start>: - 80000: d53800a8 mrs x8, mpidr_el1 - 80004: f240051f tst x8, #0x3 - 80008: 54000081 b.ne 80018 <_start+0x18> - 8000c: d5384248 mrs x8, currentel - 80010: f100211f cmp x8, #0x8 - 80014: 54000060 b.eq 80020 <_start+0x20> - 80018: d503205f wfe - 8001c: 17ffffff b 80018 <_start+0x18> - 80020: aa1f03e8 mov x8, xzr - 80024: 52800069 mov w9, #0x3 - 80028: d51ce109 msr cnthctl_el2, x9 - 8002c: d51ce068 msr cntvoff_el2, x8 - 80030: 90000008 adrp x8, 80000 <_start> - 80034: 52b0000a mov w10, #0x80000000 - 80038: 528078ab mov w11, #0x3c5 - 8003c: 52a0010c mov w12, #0x80000 - 80040: d51c110a msr hcr_el2, x10 - 80044: d51c400b msr spsr_el2, x11 - 80048: 91374108 add x8, x8, #0xdd0 - 8004c: d51c4028 msr elr_el2, x8 - 80050: d51c410c msr sp_el1, x12 - 80054: d69f03e0 eret -``` - -Looks good! Thanks zero-overhead abstractions in the [cortex-a] crate! :heart_eyes: - -[cortex-a]: https://github.com/rust-embedded/cortex-a - -## Test it - -In `main.rs`, we additionally inspect if the mask bits in `SPSR_EL2` made it to `EL1` as well: - -```console -$ make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 3 - -[ML] Requesting binary -[MP] ⏩ Pushing 15 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 -[ML] Loaded! Executing the payload now - -[ 0.703812] Booting on: Raspberry Pi 3 -[ 0.704900] Current privilege level: EL1 -[ 0.706811] Exception handling state: -[ 0.708592] Debug: Masked -[ 0.710156] SError: Masked -[ 0.711719] IRQ: Masked -[ 0.713283] FIQ: Masked -[ 0.714848] Architectural timer resolution: 52 ns -[ 0.717149] Drivers loaded: -[ 0.718496] 1. BCM GPIO -[ 0.719929] 2. BCM PL011 UART -[ 0.721623] Timer test, spinning for 1 second -[ 1.723753] Echoing input now -``` - -## Diff to previous -```diff - -diff -uNr 09_hw_debug_JTAG/src/_arch/aarch64/cpu.rs 10_privilege_level/src/_arch/aarch64/cpu.rs ---- 09_hw_debug_JTAG/src/_arch/aarch64/cpu.rs -+++ 10_privilege_level/src/_arch/aarch64/cpu.rs -@@ -21,18 +21,59 @@ - #[naked] - #[no_mangle] - pub unsafe fn _start() -> ! { -- use crate::runtime_init; -- - // Expect the boot core to start in EL2. -- if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { -- SP.set(bsp::memory::boot_core_stack_end() as u64); -- runtime_init::runtime_init() -+ if (bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id()) -+ && (CurrentEL.get() == CurrentEL::EL::EL2.value) -+ { -+ el2_to_el1_transition() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } - } - -+/// Transition from EL2 to EL1. -+/// -+/// # Safety -+/// -+/// - The HW state of EL1 must be prepared in a sound way. -+/// - Exception return from EL2 must must continue execution in EL1 with -+/// `runtime_init::runtime_init()`. -+#[inline(always)] -+unsafe fn el2_to_el1_transition() -> ! { -+ use crate::runtime_init; -+ -+ // Enable timer counter registers for EL1. -+ CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); -+ -+ // No offset for reading the counters. -+ CNTVOFF_EL2.set(0); -+ -+ // Set EL1 execution state to AArch64. -+ HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); -+ -+ // Set up a simulated exception return. -+ // -+ // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a -+ // stack pointer. -+ SPSR_EL2.write( -+ SPSR_EL2::D::Masked -+ + SPSR_EL2::A::Masked -+ + SPSR_EL2::I::Masked -+ + SPSR_EL2::F::Masked -+ + SPSR_EL2::M::EL1h, -+ ); -+ -+ // Second, let the link register point to runtime_init(). -+ ELR_EL2.set(runtime_init::runtime_init as *const () as u64); -+ -+ // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. -+ SP_EL1.set(bsp::memory::boot_core_stack_end() as u64); -+ -+ // Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. -+ asm::eret() -+} -+ - //-------------------------------------------------------------------------------------------------- - // Public Code - //-------------------------------------------------------------------------------------------------- - -diff -uNr 09_hw_debug_JTAG/src/_arch/aarch64/exception/asynchronous.rs 10_privilege_level/src/_arch/aarch64/exception/asynchronous.rs ---- 09_hw_debug_JTAG/src/_arch/aarch64/exception/asynchronous.rs -+++ 10_privilege_level/src/_arch/aarch64/exception/asynchronous.rs -@@ -0,0 +1,74 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Architectural asynchronous exception handling. -+ -+use cortex_a::regs::*; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+trait DaifField { -+ fn daif_field() -> register::Field; -+} -+ -+struct Debug; -+struct SError; -+struct IRQ; -+struct FIQ; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl DaifField for Debug { -+ fn daif_field() -> register::Field { -+ DAIF::D -+ } -+} -+ -+impl DaifField for SError { -+ fn daif_field() -> register::Field { -+ DAIF::A -+ } -+} -+ -+impl DaifField for IRQ { -+ fn daif_field() -> register::Field { -+ DAIF::I -+ } -+} -+ -+impl DaifField for FIQ { -+ fn daif_field() -> register::Field { -+ DAIF::F -+ } -+} -+ -+fn is_masked() -> bool -+where -+ T: DaifField, -+{ -+ DAIF.is_set(T::daif_field()) -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Print the AArch64 exceptions status. -+#[rustfmt::skip] -+pub fn print_state() { -+ use crate::info; -+ -+ let to_mask_str = |x| -> _ { -+ if x { "Masked" } else { "Unmasked" } -+ }; -+ -+ info!(" Debug: {}", to_mask_str(is_masked::())); -+ info!(" SError: {}", to_mask_str(is_masked::())); -+ info!(" IRQ: {}", to_mask_str(is_masked::())); -+ info!(" FIQ: {}", to_mask_str(is_masked::())); -+} - -diff -uNr 09_hw_debug_JTAG/src/_arch/aarch64/exception.rs 10_privilege_level/src/_arch/aarch64/exception.rs ---- 09_hw_debug_JTAG/src/_arch/aarch64/exception.rs -+++ 10_privilege_level/src/_arch/aarch64/exception.rs -@@ -0,0 +1,23 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Architectural synchronous and asynchronous exception handling. -+ -+use cortex_a::regs::*; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+use crate::exception::PrivilegeLevel; -+ -+/// The processing element's current privilege level. -+pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { -+ let el = CurrentEL.read_as_enum(CurrentEL::EL); -+ match el { -+ Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), -+ Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), -+ Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), -+ _ => (PrivilegeLevel::Unknown, "Unknown"), -+ } -+} - -diff -uNr 09_hw_debug_JTAG/src/exception/asynchronous.rs 10_privilege_level/src/exception/asynchronous.rs ---- 09_hw_debug_JTAG/src/exception/asynchronous.rs -+++ 10_privilege_level/src/exception/asynchronous.rs -@@ -0,0 +1,10 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Asynchronous exception handling. -+ -+#[cfg(target_arch = "aarch64")] -+#[path = "../_arch/aarch64/exception/asynchronous.rs"] -+mod arch_exception_async; -+pub use arch_exception_async::*; - -diff -uNr 09_hw_debug_JTAG/src/exception.rs 10_privilege_level/src/exception.rs ---- 09_hw_debug_JTAG/src/exception.rs -+++ 10_privilege_level/src/exception.rs -@@ -0,0 +1,26 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Synchronous and asynchronous exception handling. -+ -+#[cfg(target_arch = "aarch64")] -+#[path = "_arch/aarch64/exception.rs"] -+mod arch_exception; -+pub use arch_exception::*; -+ -+pub mod asynchronous; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Kernel privilege levels. -+#[allow(missing_docs)] -+#[derive(PartialEq)] -+pub enum PrivilegeLevel { -+ User, -+ Kernel, -+ Hypervisor, -+ Unknown, -+} - -diff -uNr 09_hw_debug_JTAG/src/main.rs 10_privilege_level/src/main.rs ---- 09_hw_debug_JTAG/src/main.rs -+++ 10_privilege_level/src/main.rs -@@ -117,6 +117,7 @@ - mod console; - mod cpu; - mod driver; -+mod exception; - mod memory; - mod panic_wait; - mod print; -@@ -147,12 +148,19 @@ - - /// The main function running after the early init. - fn kernel_main() -> ! { -+ use console::interface::All; - use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; - - info!("Booting on: {}", bsp::board_name()); - -+ let (_, privilege_level) = exception::current_privilege_level(); -+ info!("Current privilege level: {}", privilege_level); -+ -+ info!("Exception handling state:"); -+ exception::asynchronous::print_state(); -+ - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() -@@ -167,11 +175,12 @@ - info!(" {}. {}", i + 1, driver.compatible()); - } - -- // Test a failing timer case. -- time::time_manager().spin_for(Duration::from_nanos(1)); -+ info!("Timer test, spinning for 1 second"); -+ time::time_manager().spin_for(Duration::from_secs(1)); - -+ info!("Echoing input now"); - loop { -- info!("Spinning for 1 second"); -- time::time_manager().spin_for(Duration::from_secs(1)); -+ let c = bsp::console::console().read_char(); -+ bsp::console::console().write_char(c); - } - } - -``` diff --git a/10_privilege_level/build.rs b/10_privilege_level/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/10_privilege_level/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/10_privilege_level/src/_arch/aarch64/cpu.rs b/10_privilege_level/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 3e5e57530..000000000 --- a/10_privilege_level/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - // Expect the boot core to start in EL2. - if (bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id()) - && (CurrentEL.get() == CurrentEL::EL::EL2.value) - { - el2_to_el1_transition() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -/// Transition from EL2 to EL1. -/// -/// # Safety -/// -/// - The HW state of EL1 must be prepared in a sound way. -/// - Exception return from EL2 must must continue execution in EL1 with -/// `runtime_init::runtime_init()`. -#[inline(always)] -unsafe fn el2_to_el1_transition() -> ! { - use crate::runtime_init; - - // Enable timer counter registers for EL1. - CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); - - // No offset for reading the counters. - CNTVOFF_EL2.set(0); - - // Set EL1 execution state to AArch64. - HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); - - // Set up a simulated exception return. - // - // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a - // stack pointer. - SPSR_EL2.write( - SPSR_EL2::D::Masked - + SPSR_EL2::A::Masked - + SPSR_EL2::I::Masked - + SPSR_EL2::F::Masked - + SPSR_EL2::M::EL1h, - ); - - // Second, let the link register point to runtime_init(). - ELR_EL2.set(runtime_init::runtime_init as *const () as u64); - - // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. - SP_EL1.set(bsp::memory::boot_core_stack_end() as u64); - - // Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. - asm::eret() -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} diff --git a/10_privilege_level/src/_arch/aarch64/cpu/smp.rs b/10_privilege_level/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/10_privilege_level/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/10_privilege_level/src/_arch/aarch64/exception.rs b/10_privilege_level/src/_arch/aarch64/exception.rs deleted file mode 100644 index ebfef8c82..000000000 --- a/10_privilege_level/src/_arch/aarch64/exception.rs +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural synchronous and asynchronous exception handling. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use crate::exception::PrivilegeLevel; - -/// The processing element's current privilege level. -pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { - let el = CurrentEL.read_as_enum(CurrentEL::EL); - match el { - Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), - Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), - Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), - _ => (PrivilegeLevel::Unknown, "Unknown"), - } -} diff --git a/10_privilege_level/src/_arch/aarch64/exception/asynchronous.rs b/10_privilege_level/src/_arch/aarch64/exception/asynchronous.rs deleted file mode 100644 index f660544c1..000000000 --- a/10_privilege_level/src/_arch/aarch64/exception/asynchronous.rs +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural asynchronous exception handling. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -trait DaifField { - fn daif_field() -> register::Field; -} - -struct Debug; -struct SError; -struct IRQ; -struct FIQ; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl DaifField for Debug { - fn daif_field() -> register::Field { - DAIF::D - } -} - -impl DaifField for SError { - fn daif_field() -> register::Field { - DAIF::A - } -} - -impl DaifField for IRQ { - fn daif_field() -> register::Field { - DAIF::I - } -} - -impl DaifField for FIQ { - fn daif_field() -> register::Field { - DAIF::F - } -} - -fn is_masked() -> bool -where - T: DaifField, -{ - DAIF.is_set(T::daif_field()) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Print the AArch64 exceptions status. -#[rustfmt::skip] -pub fn print_state() { - use crate::info; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - info!(" Debug: {}", to_mask_str(is_masked::())); - info!(" SError: {}", to_mask_str(is_masked::())); - info!(" IRQ: {}", to_mask_str(is_masked::())); - info!(" FIQ: {}", to_mask_str(is_masked::())); -} diff --git a/10_privilege_level/src/_arch/aarch64/time.rs b/10_privilege_level/src/_arch/aarch64/time.rs deleted file mode 100644 index af98ddd01..000000000 --- a/10_privilege_level/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) - } - - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; - - Duration::from_nanos(current_count / frq) - } - - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } - - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get() as u64; - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; - } - - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); - - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); - - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} - - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); - } -} diff --git a/10_privilege_level/src/bsp.rs b/10_privilege_level/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/10_privilege_level/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/10_privilege_level/src/bsp/device_driver.rs b/10_privilege_level/src/bsp/device_driver.rs deleted file mode 100644 index ce7396f22..000000000 --- a/10_privilege_level/src/bsp/device_driver.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/10_privilege_level/src/bsp/device_driver/bcm.rs b/10_privilege_level/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 59071d5d8..000000000 --- a/10_privilege_level/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/10_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/10_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index 15bd3b78b..000000000 --- a/10_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; - use core::time::Duration; - - // The Linux 2837 GPIO driver waits 1 µs between the steps. - const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/10_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/10_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index e39bc7cdb..000000000 --- a/10_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,323 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => _reserved3), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Read one character. - let mut ret = inner.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - inner.chars_read += 1; - - ret - }) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} diff --git a/10_privilege_level/src/bsp/device_driver/common.rs b/10_privilege_level/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/10_privilege_level/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/10_privilege_level/src/bsp/raspberrypi.rs b/10_privilege_level/src/bsp/raspberrypi.rs deleted file mode 100644 index 10888d37f..000000000 --- a/10_privilege_level/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/10_privilege_level/src/bsp/raspberrypi/console.rs b/10_privilege_level/src/bsp/raspberrypi/console.rs deleted file mode 100644 index d1b60dd82..000000000 --- a/10_privilege_level/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} diff --git a/10_privilege_level/src/bsp/raspberrypi/cpu.rs b/10_privilege_level/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/10_privilege_level/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/10_privilege_level/src/bsp/raspberrypi/driver.rs b/10_privilege_level/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index fe24dd71b..000000000 --- a/10_privilege_level/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/10_privilege_level/src/bsp/raspberrypi/link.ld b/10_privilege_level/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/10_privilege_level/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/10_privilege_level/src/bsp/raspberrypi/memory.rs b/10_privilege_level/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index fae051257..000000000 --- a/10_privilege_level/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/10_privilege_level/src/console.rs b/10_privilege_level/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/10_privilege_level/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/10_privilege_level/src/cpu.rs b/10_privilege_level/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/10_privilege_level/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/10_privilege_level/src/cpu/smp.rs b/10_privilege_level/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/10_privilege_level/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/10_privilege_level/src/driver.rs b/10_privilege_level/src/driver.rs deleted file mode 100644 index e2875b876..000000000 --- a/10_privilege_level/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/10_privilege_level/src/exception.rs b/10_privilege_level/src/exception.rs deleted file mode 100644 index d2e621795..000000000 --- a/10_privilege_level/src/exception.rs +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronous and asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/exception.rs"] -mod arch_exception; -pub use arch_exception::*; - -pub mod asynchronous; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Kernel privilege levels. -#[allow(missing_docs)] -#[derive(PartialEq)] -pub enum PrivilegeLevel { - User, - Kernel, - Hypervisor, - Unknown, -} diff --git a/10_privilege_level/src/exception/asynchronous.rs b/10_privilege_level/src/exception/asynchronous.rs deleted file mode 100644 index 3c75f90a2..000000000 --- a/10_privilege_level/src/exception/asynchronous.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/exception/asynchronous.rs"] -mod arch_exception_async; -pub use arch_exception_async::*; diff --git a/10_privilege_level/src/main.rs b/10_privilege_level/src/main.rs deleted file mode 100644 index 1cc057ac8..000000000 --- a/10_privilege_level/src/main.rs +++ /dev/null @@ -1,186 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![feature(const_fn_fn_ptr_basics)] -#![feature(format_args_nl)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod driver; -mod exception; -mod memory; -mod panic_wait; -mod print; -mod runtime_init; -mod synchronization; -mod time; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order. -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use console::interface::All; - use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; - - info!("Booting on: {}", bsp::board_name()); - - let (_, privilege_level) = exception::current_privilege_level(); - info!("Current privilege level: {}", privilege_level); - - info!("Exception handling state:"); - exception::asynchronous::print_state(); - - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() - ); - - info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } - - info!("Timer test, spinning for 1 second"); - time::time_manager().spin_for(Duration::from_secs(1)); - - info!("Echoing input now"); - loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); - } -} diff --git a/10_privilege_level/src/memory.rs b/10_privilege_level/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/10_privilege_level/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/10_privilege_level/src/panic_wait.rs b/10_privilege_level/src/panic_wait.rs deleted file mode 100644 index 1386e1e23..000000000 --- a/10_privilege_level/src/panic_wait.rs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/10_privilege_level/src/print.rs b/10_privilege_level/src/print.rs deleted file mode 100644 index 8b6f3f988..000000000 --- a/10_privilege_level/src/print.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} - -/// Prints an info, with a newline. -#[macro_export] -macro_rules! info { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} - -/// Prints a warning, with a newline. -#[macro_export] -macro_rules! warn { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} diff --git a/10_privilege_level/src/runtime_init.rs b/10_privilege_level/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/10_privilege_level/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/10_privilege_level/src/synchronization.rs b/10_privilege_level/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/10_privilege_level/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/10_privilege_level/src/time.rs b/10_privilege_level/src/time.rs deleted file mode 100644 index cd3ceec33..000000000 --- a/10_privilege_level/src/time.rs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; -pub use arch_time::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); - } -} diff --git a/10_virtual_mem_part1_identity_mapping/.vscode/settings.json b/10_virtual_mem_part1_identity_mapping/.vscode/settings.json new file mode 100644 index 000000000..bfa278e9a --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/10_virtual_mem_part1_identity_mapping/Cargo.lock b/10_virtual_mem_part1_identity_mapping/Cargo.lock new file mode 100644 index 000000000..af2a0a5d5 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/Cargo.lock @@ -0,0 +1,26 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.10.0" +dependencies = [ + "aarch64-cpu", + "tock-registers", +] + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/10_virtual_mem_part1_identity_mapping/Cargo.toml b/10_virtual_mem_part1_identity_mapping/Cargo.toml new file mode 100644 index 000000000..6f12f98e8 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "mingo" +version = "0.10.0" +authors = ["Andre Richter "] +edition = "2021" + +[profile.release] +lto = true + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] + +[[bin]] +name = "kernel" +path = "src/main.rs" + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/10_virtual_mem_part1_identity_mapping/Makefile b/10_virtual_mem_part1_identity_mapping/Makefile new file mode 100644 index 000000000..9549f0920 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/Makefile @@ -0,0 +1,279 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/10_virtual_mem_part1_identity_mapping/README.CN.md b/10_virtual_mem_part1_identity_mapping/README.CN.md new file mode 100644 index 000000000..2b840e28c --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/README.CN.md @@ -0,0 +1,319 @@ +# 教程10 - 虚拟内存第一部分:将所有内容进行身份映射! + +## tl;dr + +- 打开`MMU`。 +- 使用简单的方案:静态的`64 KiB`转换表。 +- 为了教学目的,我们将数据写入重新映射的`UART`,并对其他所有内容进行`identity map`。 + +## 目录 + +- [介绍](#introduction) +- [MMU和分页理论](#MMU和分页理论) +- [方法](#方法) + * [通用内核代码:`memory/mmu.rs`](#通用内核代码:`memory/mmu.rs`) + * [BSP:`bsp/raspberrypi/memory/mmu.rs`](#bsp-bspraspberrypimemorymmurs) + * [AArch64:`_arch/aarch64/memory/*`](#aarch64-_archaarch64memory) + * [`kernel.ld`](#kernelld) +- [地址转换示例](#地址转换示例) + * [使用64 KiB页描述符进行地址转换](#使用64KiB页描述符进行地址转换) +- [零成本抽象](#零成本抽象) +- [测试](#测试) +- [相比之前的变化(diff)](#相比之前的变化(diff)) + +## 介绍 + +虚拟内存是一个非常复杂但重要且强大的主题。在本教程中,我们从简单易懂的方式开始, +通过打开`MMU`,使用静态转换表和一次性进行`identity-map` +(除了为教育目的而重新映射的`UART`之外;在下一个教程中,这将被取消)。 + +## MMU和分页理论 + +在这一点上,我们不会重新发明轮子并详细描述现代应用级处理器中分页的工作原理。 +互联网上有很多关于这个主题的优秀资源,我们鼓励您阅读其中一些以获得对该主题的高层理解。 + +继续阅读本`AArch64`特定的教程,我强烈建议您在此处停下来,首先阅读[ARM Cortex-A Series Programmer's Guide for ARMv8-A]的`第12章`, +以便在继续之前获得所有所需的`AArch64`特定知识。 + +已经阅读完`第12章`了吗?做得好 :+1:! + +[ARM Cortex-A Series Programmer's Guide for ARMv8-A]: http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf + +## 方法 + +1. 通用的`kernel`部分:`src/memory/mmu.rs`及其子模块提供了与体系结构无关的描述符类型, + 用于组合一个高级数据结构,描述内核的虚拟内存布局:`memory::mmu::KernelVirtualLayout`。 +2. `BSP`部分:`src/bsp/raspberrypi/memory/mmu.rs`包含一个`KernelVirtualLayout`的静态实例,并通过函数 + `bsp::memory::mmu::virt_mem_layout()`使其可访问。 +3. `aarch64`部分:`src/_arch/aarch64/memory/mmu.rs`及其子模块包含实际的`MMU`驱动程序。它使用`64 KiB`粒度获取 + `BSP`的高级`KernelVirtualLayout`并进行映射。 + +### 通用内核代码:`memory/mmu.rs` + +在这个文件中提供的描述符类型是构建块,用于描述不同内存区域的属性。 +例如,`R/W`(读/写)、`no-execute`(不执行)、`cached/uncached`(缓存/非缓存)等等。 + +这些描述符与硬件`MMU`的实际描述符无关。不同的`BSP`可以使用这些类型来生成内核虚拟内存布局的高级描述。 +真实硬件的实际`MMU`驱动程序将使用这些类型作为输入。 + +通过这种方式,我们在`BSP`和`_arch`代码之间实现了清晰的抽象,这样可以在不需要调整另一个的情况下进行交换。 + +### BSP: `bsp/raspberrypi/memory/mmu.rs` + +这个文件包含了一个`KernelVirtualLayout`的实例,用于存储先前提到的描述符。 +将其放在`BSP`中是正确的位置,因为它具有目标板的内存映射知识。 + +策略是只描述**不是**普通的、可缓存的DRAM的区域。然而,如果您希望,也可以定义这些区域。 +这里是一个设备MMIO区域的示例: + +```rust +TranslationDescriptor { + name: "Device MMIO", + virtual_range: mmio_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, +}, +``` + +`KernelVirtualLayout`本身实现了以下方法: + +```rust +pub fn virt_addr_properties( + &self, + virt_addr: usize, +) -> Result<(usize, AttributeFields), &'static str> +``` + +它将被`_arch/aarch64`的`MMU`代码使用,用于请求虚拟地址和转换的属性,该转换提供物理输出地址 +(返回元组中的`usize`)。该函数扫描包含查询地址的描述符,并返回第一个匹配的条目的相应结果。 +如果找不到条目,则返回普通可缓存DRAM的默认属性和输入地址,从而告诉`MMU`代码请求的地址应该是`identity mapped`。 + +由于这种默认行为,不需要定义普通可缓存DRAM区域。 + +### AArch64: `_arch/aarch64/memory/*` + +这些模块包含了`AArch64`的`MMU`驱动程序。粒度在这里被硬编码为(`64 KiB`页描述符)。 + +在`translation_table.rs`中,有一个实际的转换表结构的定义,它对`LVL2`表的数量进行了泛化。 +后者取决于目标板的内存大小。自然地,`BSP`了解目标板的这些细节,并通过常量 +`bsp::memory::mmu::KernelAddrSpace::SIZE`提供大小信息。 + +`translation_table.rs`使用这些信息来计算所需的`LVL2`表的数量。由于在`64 KiB`配置中, +一个`LVL2`表可以覆盖`512 MiB`,所以只需要将`KernelAddrSpace::SIZE`除以`512 MiB` +(有几个编译时检查确保`KernelAddrSpace::SIZE`是`512 MiB`的倍数)。 + +最终的表类型被导出为`KernelTranslationTable`。以下是来自`translation_table.rs`的相关代码: + +```rust +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, hence the "reverse" order of appearance. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], +} + +/// A translation table type for the kernel space. +pub type KernelTranslationTable = FixedSizeTranslationTable; +``` + +在`mmu.rs`中,`KernelTranslationTable`用于创建内核表的最终实例: + +```rust +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); +``` + +它们在`MMU::init()`期间通过调用`KERNEL_TABLES.populate_tt_entries()`进行填充, +该函数利用`bsp::memory::mmu::virt_mem_layout().virt_addr_properties()`和一系列实用函数,将内核通用描述符转换为 +`AArch64 MMU`硬件所需的实际`64 bit`整数条目,用于填充转换表数组。 + +一个值得注意的事情是,每个页描述符都有一个索引(`AttrIndex`),它索引到[MAIR_EL1]寄存器, +该寄存器保存了有关相应页面的缓存属性的信息。我们目前定义了普通可缓存内存和设备内存(不被缓存)。 + +[MAIR_EL1]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500d/CIHDHJBB.html + +```rust +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } +``` + +然后,[Translation Table Base Register 0 - EL1]使用`lvl2`表的基地址进行设置,同时配置[Translation Control Register - EL1]: + +```rust +// Set the "Translation Table Base Register". +TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); + +self.configure_translation_control(); +``` + +最后,通过[System Control Register - EL1]打开`MMU`。最后一步还启用了数据和指令的缓存。 + +[Translation Table Base Register 0 - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/ttbr0_el1.rs.html +[Translation Control Register - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/tcr_el1.rs.html +[System Control Register - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/sctlr_el1.rs.html + +### `kernel.ld` + +我们需要将`code`段对齐到`64 KiB`,这样它就不会与下一个需要读/写属性而不是读/执行属性的部分重叠。 + +```ld.s +. = ALIGN(PAGE_SIZE); +__code_end_exclusive = .; +``` + +这会增加二进制文件的大小,但考虑到与传统的`4 KiB`粒度相比,它显著减少了静态分页条目的数量,这是一个小小的代价。 + +## 地址转换示例 + +出于教育目的,定义了一个布局,允许通过两个不同的虚拟地址访问`UART` +- 由于我们对整个`Device MMIO`区域进行了身份映射,所以在`MMU`打开后,可以通过断言其物理基地址 + (`0x3F20_1000`或`0xFA20_1000`,取决于使用的是哪个RPi版本)来访问它。 +- 此外,它还映射到第一个`512 MiB`中的最后一个`64 KiB`槽位,使其可以通过基地址`0x1FFF_1000`访问。 + +以下块图可视化了第二个映射的底层转换。 + +### 使用64KiB页描述符进行地址转换 + +Page Tables 64KiB + +## 零成本抽象 + +初始化代码再次是展示Rust零成本抽象在嵌入式编程中巨大潜力的一个很好的例子[[1]][[2]]。 + +让我们再次看一下使用[aarch64-cpu]crate设置`MAIR_EL1`寄存器的代码片段: + +[1]: https://blog.rust-lang.org/2015/05/11/traits.html +[2]: https://ruudvanasseldonk.com/2016/11/30/zero-cost-abstractions +[aarch64-cpu]: https://crates.io/crates/aarch64-cpu + +```rust +/// Setup function for the MAIR_EL1 register. +fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); +} +``` + +这段代码具有超强的表达能力,它利用`traits`,不同的`types`和`constants`来提供类型安全的寄存器操作。 + +最后,此代码根据数据表将寄存器的前四个字节设置为特定值。查看生成的代码, +我们可以看到,尽管有所有的类型安全和抽象,但它可以归结为两条汇编指令: + +```text + 800a8: 529fe089 mov w9, #0xff04 // #65284 + 800ac: d518a209 msr mair_el1, x9 +``` + +## 测试 + +打开虚拟内存现在是我们在内核初始化过程中要做的第一件事: + +```rust +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + panic!("MMU: {}", string); + } +``` + +稍后在引导过程中,可以观察到有关映射的打印: + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 64 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.811167] mingo version 0.10.0 +[ 0.811374] Booting on: Raspberry Pi 3 +[ 0.811829] MMU online. Special regions: +[ 0.812306] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data +[ 0.813324] 0x1fff0000 - 0x1fffffff | 64 KiB | Dev RW PXN | Remapped Device MMIO +[ 0.814310] 0x3f000000 - 0x4000ffff | 17 MiB | Dev RW PXN | Device MMIO +[ 0.815198] Current privilege level: EL1 +[ 0.815675] Exception handling state: +[ 0.816119] Debug: Masked +[ 0.816509] SError: Masked +[ 0.816899] IRQ: Masked +[ 0.817289] FIQ: Masked +[ 0.817679] Architectural timer resolution: 52 ns +[ 0.818253] Drivers loaded: +[ 0.818589] 1. BCM PL011 UART +[ 0.819011] 2. BCM GPIO +[ 0.819369] Timer test, spinning for 1 second +[ !!! ] Writing through the remapped UART at 0x1FFF_1000 +[ 1.820409] Echoing input now +``` + +## 相比之前的变化(diff) +请检查[英文版本](README.md#diff-to-previous),这是最新的。 diff --git a/10_virtual_mem_part1_identity_mapping/README.md b/10_virtual_mem_part1_identity_mapping/README.md new file mode 100644 index 000000000..498ef1116 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/README.md @@ -0,0 +1,1479 @@ +# Tutorial 10 - Virtual Memory Part 1: Identity Map All The Things! + +## tl;dr + +- The `MMU` is turned on. +- A simple scheme is used: Static `64 KiB` translation tables. +- For educational purposes, we write to a remapped `UART`, and `identity map` everything else. + +## Table of Contents + +- [Introduction](#introduction) +- [MMU and paging theory](#mmu-and-paging-theory) +- [Approach](#approach) + * [Generic Kernel code: `memory/mmu.rs`](#generic-kernel-code-memorymmurs) + * [BSP: `bsp/raspberrypi/memory/mmu.rs`](#bsp-bspraspberrypimemorymmurs) + * [AArch64: `_arch/aarch64/memory/*`](#aarch64-_archaarch64memory) + * [`kernel.ld`](#kernelld) +- [Address translation examples](#address-translation-examples) + * [Address translation using a 64 KiB page descriptor](#address-translation-using-a-64-kib-page-descriptor) +- [Zero-cost abstraction](#zero-cost-abstraction) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +Virtual memory is an immensely complex, but important and powerful topic. In this tutorial, we start +slow and easy by switching on the `MMU`, using static translation tables and `identity-map` +everything at once (except for the `UART`, which we also remap a second time for educational +purposes; This will be gone again in the next tutorial). + +## MMU and paging theory + +At this point, we will not re-invent the wheel and go into detailed descriptions of how paging in +modern application-grade processors works. The internet is full of great resources regarding this +topic, and we encourage you to read some of it to get a high-level understanding of the topic. + +To follow the rest of this `AArch64` specific tutorial, I strongly recommend that you stop right +here and first read `Chapter 12` of the [ARM Cortex-A Series Programmer's Guide for ARMv8-A] before +you continue. This will set you up with all the `AArch64`-specific knowledge needed to follow along. + +Back from reading `Chapter 12` already? Good job :+1:! + +[ARM Cortex-A Series Programmer's Guide for ARMv8-A]: http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf + +## Approach + +1. The generic `kernel` part: `src/memory/mmu.rs` and its submodules provide architecture-agnostic + descriptor types for composing a high-level data structure that describes the kernel's virtual + memory layout: `memory::mmu::KernelVirtualLayout`. +2. The `BSP` part: `src/bsp/raspberrypi/memory/mmu.rs` contains a static instance of + `KernelVirtualLayout` and makes it accessible through the function + `bsp::memory::mmu::virt_mem_layout()`. +3. The `aarch64` part: `src/_arch/aarch64/memory/mmu.rs` and its submodules contain the actual `MMU` + driver. It picks up the `BSP`'s high-level `KernelVirtualLayout` and maps it using a `64 KiB` + granule. + +### Generic Kernel code: `memory/mmu.rs` + +The descriptor types provided in this file are building blocks which help to describe attributes of +different memory regions. For example, `R/W`, `no-execute`, `cached/uncached`, and so on. + +The descriptors are agnostic of the hardware `MMU`'s actual descriptors. Different `BSP`s can use +these types to produce a high-level description of the kernel's virtual memory layout. The actual +`MMU` driver for the real HW will consume these types as an input. + +This way, we achieve a clean abstraction between `BSP` and `_arch` code, which allows exchanging one +without needing to adapt the other. + +### BSP: `bsp/raspberrypi/memory/mmu.rs` + +This file contains an instance of `KernelVirtualLayout`, which stores the descriptors mentioned +previously. The `BSP` is the correct place to do this, because it has knowledge of the target +board's memory map. + +The policy is to only describe regions that are **not** ordinary, normal cacheable DRAM. However, +nothing prevents you from defining those too if you wish to. Here is an example for the device MMIO +region: + +```rust +TranslationDescriptor { + name: "Device MMIO", + virtual_range: mmio_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, +}, +``` + +`KernelVirtualLayout` itself implements the following method: + +```rust +pub fn virt_addr_properties( + &self, + virt_addr: usize, +) -> Result<(usize, AttributeFields), &'static str> +``` + +It will be used by `_arch/aarch64`'s `MMU` code to request attributes for a virtual address and the +translation, which delivers the physical output address (the `usize` in the return-tuple). The +function scans for a descriptor that contains the queried address, and returns the respective +findings for the first entry that is a hit. If no entry is found, it returns default attributes for +normal cacheable DRAM and the input address, hence telling the `MMU` code that the requested +address should be `identity mapped`. + +Due to this default behavior, it is not needed to define normal cacheable DRAM regions. + +### AArch64: `_arch/aarch64/memory/*` + +These modules contain the `AArch64` `MMU` driver. The granule is hardcoded here (`64 KiB` page +descriptors). + +In `translation_table.rs`, there is a definition of the actual translation table struct which is +generic over the number of `LVL2` tables. The latter depends on the size of the target board's +memory. Naturally, the `BSP` knows these details about the target board, and provides the size +through the constant `bsp::memory::mmu::KernelAddrSpace::SIZE`. + +This information is used by `translation_table.rs` to calculate the number of needed `LVL2` tables. +Since one `LVL2` table in a `64 KiB` configuration covers `512 MiB`, all that needs to be done is to +divide `KernelAddrSpace::SIZE` by `512 MiB` (there are several compile-time checks in place that +ensure that `KernelAddrSpace::SIZE` is a multiple of `512 MiB`). + +The final table type is exported as `KernelTranslationTable`. Below is the respective excerpt from +`translation_table.rs`: + +```rust +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, hence the "reverse" order of appearance. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], +} + +/// A translation table type for the kernel space. +pub type KernelTranslationTable = FixedSizeTranslationTable; +``` + +In `mmu.rs`, `KernelTranslationTable` is then used to create the final instance of the kernel's +tables: + +```rust +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); +``` + +They are populated during `MMU::init()` by calling `KERNEL_TABLES.populate_tt_entries()`, which +utilizes `bsp::memory::mmu::virt_mem_layout().virt_addr_properties()` and a bunch of utility +functions that convert the kernel generic descriptors to the actual `64 bit` integer entries needed +by the `AArch64 MMU` hardware for the translation table arrays. + +One notable thing is that each page descriptor has an entry (`AttrIndex`) that indexes into the +[MAIR_EL1] register, which holds information about the cacheability of the respective page. We +currently define normal cacheable memory and device memory (which is not cached). + +[MAIR_EL1]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500d/CIHDHJBB.html + +```rust +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } +``` + +Afterwards, the [Translation Table Base Register 0 - EL1] is set up with the base address of the +`lvl2` tables and the [Translation Control Register - EL1] is configured: + +```rust +// Set the "Translation Table Base Register". +TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); + +self.configure_translation_control(); +``` + +Finally, the `MMU` is turned on through the [System Control Register - EL1]. The last step also +enables caching for data and instructions. + +[Translation Table Base Register 0 - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/ttbr0_el1.rs.html +[Translation Control Register - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/tcr_el1.rs.html +[System Control Register - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/sctlr_el1.rs.html + +### `kernel.ld` + +We need to align the `code` segment to `64 KiB` so that it doesn't overlap with the next section +that needs read/write attributes instead of read/execute attributes: + +```ld.s +. = ALIGN(PAGE_SIZE); +__code_end_exclusive = .; +``` + +This blows up the binary in size, but is a small price to pay considering that it reduces the amount +of static paging entries significantly, when compared to the classical `4 KiB` granule. + +## Address translation examples + +For educational purposes, a layout is defined which allows to access the `UART` via two different +virtual addresses: +- Since we identity map the whole `Device MMIO` region, it is accessible by asserting its physical + base address (`0x3F20_1000` or `0xFA20_1000` depending on which RPi you use) after the `MMU` is + turned on. +- Additionally, it is also mapped into the last `64 KiB` slot in the first `512 MiB`, making it + accessible through base address `0x1FFF_1000`. + +The following block diagram visualizes the underlying translation for the second mapping. + +### Address translation using a 64 KiB page descriptor + +Page Tables 64KiB + +## Zero-cost abstraction + +The MMU init code is again a good example to see the great potential of Rust's zero-cost +abstractions[[1]][[2]] for embedded programming. + +Let's take a look again at the piece of code for setting up the `MAIR_EL1` register using the +[aarch64-cpu] crate: + +[1]: https://blog.rust-lang.org/2015/05/11/traits.html +[2]: https://ruudvanasseldonk.com/2016/11/30/zero-cost-abstractions +[aarch64-cpu]: https://crates.io/crates/aarch64-cpu + +```rust +/// Setup function for the MAIR_EL1 register. +fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); +} +``` + +This piece of code is super expressive, and it makes use of `traits`, different `types` and +`constants` to provide type-safe register manipulation. + +In the end, this code sets the first four bytes of the register to certain values according to the +data sheet. Looking at the generated code, we can see that despite all the type-safety and +abstractions, it boils down to two assembly instructions: + +```text + 800a8: 529fe089 mov w9, #0xff04 // #65284 + 800ac: d518a209 msr mair_el1, x9 +``` + +## Test it + +Turning on virtual memory is now the first thing we do during kernel init: + +```rust +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + panic!("MMU: {}", string); + } +``` + +Later in the boot process, prints about the mappings can be observed: + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 64 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.811167] mingo version 0.10.0 +[ 0.811374] Booting on: Raspberry Pi 3 +[ 0.811829] MMU online. Special regions: +[ 0.812306] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data +[ 0.813324] 0x1fff0000 - 0x1fffffff | 64 KiB | Dev RW PXN | Remapped Device MMIO +[ 0.814310] 0x3f000000 - 0x4000ffff | 17 MiB | Dev RW PXN | Device MMIO +[ 0.815198] Current privilege level: EL1 +[ 0.815675] Exception handling state: +[ 0.816119] Debug: Masked +[ 0.816509] SError: Masked +[ 0.816899] IRQ: Masked +[ 0.817289] FIQ: Masked +[ 0.817679] Architectural timer resolution: 52 ns +[ 0.818253] Drivers loaded: +[ 0.818589] 1. BCM PL011 UART +[ 0.819011] 2. BCM GPIO +[ 0.819369] Timer test, spinning for 1 second +[ !!! ] Writing through the remapped UART at 0x1FFF_1000 +[ 1.820409] Echoing input now +``` + +## Diff to previous +```diff + +diff -uNr 09_privilege_level/Cargo.toml 10_virtual_mem_part1_identity_mapping/Cargo.toml +--- 09_privilege_level/Cargo.toml ++++ 10_virtual_mem_part1_identity_mapping/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.9.0" ++version = "0.10.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 09_privilege_level/src/_arch/aarch64/memory/mmu/translation_table.rs 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu/translation_table.rs +--- 09_privilege_level/src/_arch/aarch64/memory/mmu/translation_table.rs ++++ 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu/translation_table.rs +@@ -0,0 +1,292 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2021-2023 Andre Richter ++ ++//! Architectural translation table. ++//! ++//! Only 64 KiB granule is supported. ++//! ++//! # Orientation ++//! ++//! Since arch modules are imported into generic modules using the path attribute, the path of this ++//! file is: ++//! ++//! crate::memory::mmu::translation_table::arch_translation_table ++ ++use crate::{ ++ bsp, memory, ++ memory::mmu::{ ++ arch_mmu::{Granule512MiB, Granule64KiB}, ++ AccessPermissions, AttributeFields, MemAttributes, ++ }, ++}; ++use core::convert; ++use tock_registers::{ ++ interfaces::{Readable, Writeable}, ++ register_bitfields, ++ registers::InMemoryRegister, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. ++register_bitfields! {u64, ++ STAGE1_TABLE_DESCRIPTOR [ ++ /// Physical address of the next descriptor. ++ NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] ++ ++ TYPE OFFSET(1) NUMBITS(1) [ ++ Block = 0, ++ Table = 1 ++ ], ++ ++ VALID OFFSET(0) NUMBITS(1) [ ++ False = 0, ++ True = 1 ++ ] ++ ] ++} ++ ++// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. ++register_bitfields! {u64, ++ STAGE1_PAGE_DESCRIPTOR [ ++ /// Unprivileged execute-never. ++ UXN OFFSET(54) NUMBITS(1) [ ++ False = 0, ++ True = 1 ++ ], ++ ++ /// Privileged execute-never. ++ PXN OFFSET(53) NUMBITS(1) [ ++ False = 0, ++ True = 1 ++ ], ++ ++ /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). ++ OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] ++ ++ /// Access flag. ++ AF OFFSET(10) NUMBITS(1) [ ++ False = 0, ++ True = 1 ++ ], ++ ++ /// Shareability field. ++ SH OFFSET(8) NUMBITS(2) [ ++ OuterShareable = 0b10, ++ InnerShareable = 0b11 ++ ], ++ ++ /// Access Permissions. ++ AP OFFSET(6) NUMBITS(2) [ ++ RW_EL1 = 0b00, ++ RW_EL1_EL0 = 0b01, ++ RO_EL1 = 0b10, ++ RO_EL1_EL0 = 0b11 ++ ], ++ ++ /// Memory attributes index into the MAIR_EL1 register. ++ AttrIndx OFFSET(2) NUMBITS(3) [], ++ ++ TYPE OFFSET(1) NUMBITS(1) [ ++ Reserved_Invalid = 0, ++ Page = 1 ++ ], ++ ++ VALID OFFSET(0) NUMBITS(1) [ ++ False = 0, ++ True = 1 ++ ] ++ ] ++} ++ ++/// A table descriptor for 64 KiB aperture. ++/// ++/// The output points to the next table. ++#[derive(Copy, Clone)] ++#[repr(C)] ++struct TableDescriptor { ++ value: u64, ++} ++ ++/// A page descriptor with 64 KiB aperture. ++/// ++/// The output points to physical memory. ++#[derive(Copy, Clone)] ++#[repr(C)] ++struct PageDescriptor { ++ value: u64, ++} ++ ++trait StartAddr { ++ fn phys_start_addr_u64(&self) -> u64; ++ fn phys_start_addr_usize(&self) -> usize; ++} ++ ++const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB ++/// aligned, so the lvl3 is put first. ++#[repr(C)] ++#[repr(align(65536))] ++pub struct FixedSizeTranslationTable { ++ /// Page descriptors, covering 64 KiB windows per entry. ++ lvl3: [[PageDescriptor; 8192]; NUM_TABLES], ++ ++ /// Table descriptors, covering 512 MiB windows. ++ lvl2: [TableDescriptor; NUM_TABLES], ++} ++ ++/// A translation table type for the kernel space. ++pub type KernelTranslationTable = FixedSizeTranslationTable; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++// The binary is still identity mapped, so we don't need to convert here. ++impl StartAddr for [T; N] { ++ fn phys_start_addr_u64(&self) -> u64 { ++ self as *const T as u64 ++ } ++ ++ fn phys_start_addr_usize(&self) -> usize { ++ self as *const _ as usize ++ } ++} ++ ++impl TableDescriptor { ++ /// Create an instance. ++ /// ++ /// Descriptor is invalid by default. ++ pub const fn new_zeroed() -> Self { ++ Self { value: 0 } ++ } ++ ++ /// Create an instance pointing to the supplied address. ++ pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { ++ let val = InMemoryRegister::::new(0); ++ ++ let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; ++ val.write( ++ STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) ++ + STAGE1_TABLE_DESCRIPTOR::TYPE::Table ++ + STAGE1_TABLE_DESCRIPTOR::VALID::True, ++ ); ++ ++ TableDescriptor { value: val.get() } ++ } ++} ++ ++/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. ++impl convert::From ++ for tock_registers::fields::FieldValue ++{ ++ fn from(attribute_fields: AttributeFields) -> Self { ++ // Memory attributes. ++ let mut desc = match attribute_fields.mem_attributes { ++ MemAttributes::CacheableDRAM => { ++ STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable ++ + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) ++ } ++ MemAttributes::Device => { ++ STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable ++ + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) ++ } ++ }; ++ ++ // Access Permissions. ++ desc += match attribute_fields.acc_perms { ++ AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, ++ AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, ++ }; ++ ++ // The execute-never attribute is mapped to PXN in AArch64. ++ desc += if attribute_fields.execute_never { ++ STAGE1_PAGE_DESCRIPTOR::PXN::True ++ } else { ++ STAGE1_PAGE_DESCRIPTOR::PXN::False ++ }; ++ ++ // Always set unprivileged exectue-never as long as userspace is not implemented yet. ++ desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; ++ ++ desc ++ } ++} ++ ++impl PageDescriptor { ++ /// Create an instance. ++ /// ++ /// Descriptor is invalid by default. ++ pub const fn new_zeroed() -> Self { ++ Self { value: 0 } ++ } ++ ++ /// Create an instance. ++ pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { ++ let val = InMemoryRegister::::new(0); ++ ++ let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; ++ val.write( ++ STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) ++ + STAGE1_PAGE_DESCRIPTOR::AF::True ++ + STAGE1_PAGE_DESCRIPTOR::TYPE::Page ++ + STAGE1_PAGE_DESCRIPTOR::VALID::True ++ + (*attribute_fields).into(), ++ ); ++ ++ Self { value: val.get() } ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl FixedSizeTranslationTable { ++ /// Create an instance. ++ pub const fn new() -> Self { ++ // Can't have a zero-sized address space. ++ assert!(NUM_TABLES > 0); ++ ++ Self { ++ lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], ++ lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], ++ } ++ } ++ ++ /// Iterates over all static translation table entries and fills them at once. ++ /// ++ /// # Safety ++ /// ++ /// - Modifies a `static mut`. Ensure it only happens from here. ++ pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { ++ for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { ++ *l2_entry = ++ TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); ++ ++ for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { ++ let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); ++ ++ let (phys_output_addr, attribute_fields) = ++ bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; ++ ++ *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); ++ } ++ } ++ ++ Ok(()) ++ } ++ ++ /// The translation table's base address to be used for programming the MMU. ++ pub fn phys_base_address(&self) -> u64 { ++ self.lvl2.phys_start_addr_u64() ++ } ++} + +diff -uNr 09_privilege_level/src/_arch/aarch64/memory/mmu.rs 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs +--- 09_privilege_level/src/_arch/aarch64/memory/mmu.rs ++++ 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs +@@ -0,0 +1,165 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Memory Management Unit Driver. ++//! ++//! Only 64 KiB granule is supported. ++//! ++//! # Orientation ++//! ++//! Since arch modules are imported into generic modules using the path attribute, the path of this ++//! file is: ++//! ++//! crate::memory::mmu::arch_mmu ++ ++use crate::{ ++ bsp, memory, ++ memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, ++}; ++use aarch64_cpu::{asm::barrier, registers::*}; ++use core::intrinsics::unlikely; ++use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Memory Management Unit type. ++struct MemoryManagementUnit; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; ++pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; ++ ++/// Constants for indexing the MAIR_EL1. ++#[allow(dead_code)] ++pub mod mair { ++ pub const DEVICE: u64 = 0; ++ pub const NORMAL: u64 = 1; ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++/// The kernel translation tables. ++/// ++/// # Safety ++/// ++/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". ++static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); ++ ++static MMU: MemoryManagementUnit = MemoryManagementUnit; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl memory::mmu::AddressSpace { ++ /// Checks for architectural restrictions. ++ pub const fn arch_address_space_size_sanity_checks() { ++ // Size must be at least one full 512 MiB table. ++ assert!((AS_SIZE modulo Granule512MiB::SIZE) == 0); ++ ++ // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 ++ // version. ++ assert!(AS_SIZE <= (1 << 48)); ++ } ++} ++ ++impl MemoryManagementUnit { ++ /// Setup function for the MAIR_EL1 register. ++ fn set_up_mair(&self) { ++ // Define the memory types being mapped. ++ MAIR_EL1.write( ++ // Attribute 1 - Cacheable normal DRAM. ++ MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + ++ MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + ++ ++ // Attribute 0 - Device. ++ MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ++ ); ++ } ++ ++ /// Configure various settings of stage 1 of the EL1 translation regime. ++ fn configure_translation_control(&self) { ++ let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; ++ ++ TCR_EL1.write( ++ TCR_EL1::TBI0::Used ++ + TCR_EL1::IPS::Bits_40 ++ + TCR_EL1::TG0::KiB_64 ++ + TCR_EL1::SH0::Inner ++ + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable ++ + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable ++ + TCR_EL1::EPD0::EnableTTBR0Walks ++ + TCR_EL1::A1::TTBR0 ++ + TCR_EL1::T0SZ.val(t0sz) ++ + TCR_EL1::EPD1::DisableTTBR1Walks, ++ ); ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Return a reference to the MMU instance. ++pub fn mmu() -> &'static impl memory::mmu::interface::MMU { ++ &MMU ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++use memory::mmu::MMUEnableError; ++ ++impl memory::mmu::interface::MMU for MemoryManagementUnit { ++ unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { ++ if unlikely(self.is_enabled()) { ++ return Err(MMUEnableError::AlreadyEnabled); ++ } ++ ++ // Fail early if translation granule is not supported. ++ if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { ++ return Err(MMUEnableError::Other( ++ "Translation granule not supported in HW", ++ )); ++ } ++ ++ // Prepare the memory attribute indirection register. ++ self.set_up_mair(); ++ ++ // Populate translation tables. ++ KERNEL_TABLES ++ .populate_tt_entries() ++ .map_err(MMUEnableError::Other)?; ++ ++ // Set the "Translation Table Base Register". ++ TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); ++ ++ self.configure_translation_control(); ++ ++ // Switch the MMU on. ++ // ++ // First, force all previous changes to be seen before the MMU is enabled. ++ barrier::isb(barrier::SY); ++ ++ // Enable the MMU and turn on data and instruction caching. ++ SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); ++ ++ // Force MMU init to complete before next instruction. ++ barrier::isb(barrier::SY); ++ ++ Ok(()) ++ } ++ ++ #[inline(always)] ++ fn is_enabled(&self) -> bool { ++ SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) ++ } ++} + +diff -uNr 09_privilege_level/src/bsp/raspberrypi/kernel.ld 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/kernel.ld +--- 09_privilege_level/src/bsp/raspberrypi/kernel.ld ++++ 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/kernel.ld +@@ -3,6 +3,9 @@ + * Copyright (c) 2018-2023 Andre Richter + */ + ++PAGE_SIZE = 64K; ++PAGE_MASK = PAGE_SIZE - 1; ++ + __rpi_phys_dram_start_addr = 0; + + /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +@@ -42,9 +45,12 @@ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + ++ ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") ++ + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ ++ __code_start = .; + .text : + { + KEEP(*(.text._start)) +@@ -55,6 +61,9 @@ + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + ++ . = ALIGN(PAGE_SIZE); ++ __code_end_exclusive = .; ++ + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + +diff -uNr 09_privilege_level/src/bsp/raspberrypi/memory/mmu.rs 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs +--- 09_privilege_level/src/bsp/raspberrypi/memory/mmu.rs ++++ 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs +@@ -0,0 +1,86 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! BSP Memory Management Unit. ++ ++use super::map as memory_map; ++use crate::memory::mmu::*; ++use core::ops::RangeInclusive; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// The kernel's address space defined by this BSP. ++pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; ++ ++const NUM_MEM_RANGES: usize = 3; ++ ++/// The virtual memory layout. ++/// ++/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. ++/// It is agnostic of the paging granularity that the architecture's MMU will use. ++pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( ++ memory_map::END_INCLUSIVE, ++ [ ++ TranslationDescriptor { ++ name: "Kernel code and RO data", ++ virtual_range: code_range_inclusive, ++ physical_range_translation: Translation::Identity, ++ attribute_fields: AttributeFields { ++ mem_attributes: MemAttributes::CacheableDRAM, ++ acc_perms: AccessPermissions::ReadOnly, ++ execute_never: false, ++ }, ++ }, ++ TranslationDescriptor { ++ name: "Remapped Device MMIO", ++ virtual_range: remapped_mmio_range_inclusive, ++ physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), ++ attribute_fields: AttributeFields { ++ mem_attributes: MemAttributes::Device, ++ acc_perms: AccessPermissions::ReadWrite, ++ execute_never: true, ++ }, ++ }, ++ TranslationDescriptor { ++ name: "Device MMIO", ++ virtual_range: mmio_range_inclusive, ++ physical_range_translation: Translation::Identity, ++ attribute_fields: AttributeFields { ++ mem_attributes: MemAttributes::Device, ++ acc_perms: AccessPermissions::ReadWrite, ++ execute_never: true, ++ }, ++ }, ++ ], ++); ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++fn code_range_inclusive() -> RangeInclusive { ++ // Notice the subtraction to turn the exclusive end into an inclusive end. ++ #[allow(clippy::range_minus_one)] ++ RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) ++} ++ ++fn remapped_mmio_range_inclusive() -> RangeInclusive { ++ // The last 64 KiB slot in the first 512 MiB ++ RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) ++} ++ ++fn mmio_range_inclusive() -> RangeInclusive { ++ RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Return a reference to the virtual memory layout. ++pub fn virt_mem_layout() -> &'static KernelVirtualLayout { ++ &LAYOUT ++} + +diff -uNr 09_privilege_level/src/bsp/raspberrypi/memory.rs 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs +--- 09_privilege_level/src/bsp/raspberrypi/memory.rs ++++ 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs +@@ -3,6 +3,45 @@ + // Copyright (c) 2018-2023 Andre Richter + + //! BSP Memory Management. ++//! ++//! The physical memory layout. ++//! ++//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used ++//! as the boot core's stack. ++//! ++//! +---------------------------------------+ ++//! | | 0x0 ++//! | | ^ ++//! | Boot-core Stack | | stack ++//! | | | growth ++//! | | | direction ++//! +---------------------------------------+ ++//! | | code_start @ 0x8_0000 ++//! | .text | ++//! | .rodata | ++//! | .got | ++//! | | ++//! +---------------------------------------+ ++//! | | code_end_exclusive ++//! | .data | ++//! | .bss | ++//! | | ++//! +---------------------------------------+ ++//! | | ++//! | | ++pub mod mmu; ++ ++use core::cell::UnsafeCell; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++// Symbols from the linker script. ++extern "Rust" { ++ static __code_start: UnsafeCell<()>; ++ static __code_end_exclusive: UnsafeCell<()>; ++} + + //-------------------------------------------------------------------------------------------------- + // Public Definitions +@@ -11,6 +50,20 @@ + /// The board's physical memory map. + #[rustfmt::skip] + pub(super) mod map { ++ /// The inclusive end address of the memory map. ++ /// ++ /// End address + 1 must be power of two. ++ /// ++ /// # Note ++ /// ++ /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for ++ /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. ++ /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. ++ /// ++ /// However, making this trade-off has the downside of making it possible for the CPU to assert a ++ /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on ++ /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. ++ pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; +@@ -23,6 +76,7 @@ + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; ++ pub const END_INCLUSIVE: usize = 0x4000_FFFF; + } + + /// Physical devices. +@@ -33,5 +87,29 @@ + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; ++ pub const END_INCLUSIVE: usize = 0xFF84_FFFF; + } + } ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Start page address of the code segment. ++/// ++/// # Safety ++/// ++/// - Value is provided by the linker script and must be trusted as-is. ++#[inline(always)] ++fn code_start() -> usize { ++ unsafe { __code_start.get() as usize } ++} ++ ++/// Exclusive end page address of the code segment. ++/// # Safety ++/// ++/// - Value is provided by the linker script and must be trusted as-is. ++#[inline(always)] ++fn code_end_exclusive() -> usize { ++ unsafe { __code_end_exclusive.get() as usize } ++} + +diff -uNr 09_privilege_level/src/bsp.rs 10_virtual_mem_part1_identity_mapping/src/bsp.rs +--- 09_privilege_level/src/bsp.rs ++++ 10_virtual_mem_part1_identity_mapping/src/bsp.rs +@@ -4,7 +4,7 @@ + + //! Conditional reexporting of Board Support Packages. + +-mod device_driver; ++pub mod device_driver; + + #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] + mod raspberrypi; + +diff -uNr 09_privilege_level/src/common.rs 10_virtual_mem_part1_identity_mapping/src/common.rs +--- 09_privilege_level/src/common.rs ++++ 10_virtual_mem_part1_identity_mapping/src/common.rs +@@ -0,0 +1,22 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! General purpose code. ++ ++/// Convert a size into human readable format. ++pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { ++ const KIB: usize = 1024; ++ const MIB: usize = 1024 * 1024; ++ const GIB: usize = 1024 * 1024 * 1024; ++ ++ if (size / GIB) > 0 { ++ (size.div_ceil(GIB), "GiB") ++ } else if (size / MIB) > 0 { ++ (size.div_ceil(MIB), "MiB") ++ } else if (size / KIB) > 0 { ++ (size.div_ceil(KIB), "KiB") ++ } else { ++ (size, "Byte") ++ } ++} + +diff -uNr 09_privilege_level/src/main.rs 10_virtual_mem_part1_identity_mapping/src/main.rs +--- 09_privilege_level/src/main.rs ++++ 10_virtual_mem_part1_identity_mapping/src/main.rs +@@ -107,9 +107,12 @@ + //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + + #![allow(clippy::upper_case_acronyms)] ++#![allow(incomplete_features)] + #![feature(asm_const)] + #![feature(const_option)] ++#![feature(core_intrinsics)] + #![feature(format_args_nl)] ++#![feature(int_roundings)] + #![feature(nonzero_min_max)] + #![feature(panic_info_message)] + #![feature(trait_alias)] +@@ -118,10 +121,12 @@ + #![no_std] + + mod bsp; ++mod common; + mod console; + mod cpu; + mod driver; + mod exception; ++mod memory; + mod panic_wait; + mod print; + mod synchronization; +@@ -132,8 +137,17 @@ + /// # Safety + /// + /// - Only a single core must be active and running this function. +-/// - The init calls in this function must appear in the correct order. ++/// - The init calls in this function must appear in the correct order: ++/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, ++/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ ++/// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. + unsafe fn kernel_init() -> ! { ++ use memory::mmu::interface::MMU; ++ ++ if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { ++ panic!("MMU: {}", string); ++ } ++ + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); +@@ -149,7 +163,7 @@ + + /// The main function running after the early init. + fn kernel_main() -> ! { +- use console::console; ++ use console::{console, interface::Write}; + use core::time::Duration; + + info!( +@@ -159,6 +173,9 @@ + ); + info!("Booting on: {}", bsp::board_name()); + ++ info!("MMU online. Special regions:"); ++ bsp::memory::mmu::virt_mem_layout().print_layout(); ++ + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + +@@ -176,6 +193,13 @@ + info!("Timer test, spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); + ++ let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; ++ writeln!( ++ remapped_uart, ++ "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" ++ ) ++ .unwrap(); ++ + info!("Echoing input now"); + + // Discard any spurious received characters before going into echo mode. + +diff -uNr 09_privilege_level/src/memory/mmu/translation_table.rs 10_virtual_mem_part1_identity_mapping/src/memory/mmu/translation_table.rs +--- 09_privilege_level/src/memory/mmu/translation_table.rs ++++ 10_virtual_mem_part1_identity_mapping/src/memory/mmu/translation_table.rs +@@ -0,0 +1,14 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2021-2023 Andre Richter ++ ++//! Translation table. ++ ++#[cfg(target_arch = "aarch64")] ++#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] ++mod arch_translation_table; ++ ++//-------------------------------------------------------------------------------------------------- ++// Architectural Public Reexports ++//-------------------------------------------------------------------------------------------------- ++pub use arch_translation_table::KernelTranslationTable; + +diff -uNr 09_privilege_level/src/memory/mmu.rs 10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs +--- 09_privilege_level/src/memory/mmu.rs ++++ 10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs +@@ -0,0 +1,253 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Memory Management Unit. ++//! ++//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file ++//! provides types for composing an architecture-agnostic description of the kernel's virtual memory ++//! layout. ++//! ++//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` ++//! function. ++//! ++//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and ++//! install respective translation tables. ++ ++#[cfg(target_arch = "aarch64")] ++#[path = "../_arch/aarch64/memory/mmu.rs"] ++mod arch_mmu; ++ ++mod translation_table; ++ ++use crate::common; ++use core::{fmt, ops::RangeInclusive}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Architectural Public Reexports ++//-------------------------------------------------------------------------------------------------- ++pub use arch_mmu::mmu; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// MMU enable errors variants. ++#[allow(missing_docs)] ++#[derive(Debug)] ++pub enum MMUEnableError { ++ AlreadyEnabled, ++ Other(&'static str), ++} ++ ++/// Memory Management interfaces. ++pub mod interface { ++ use super::*; ++ ++ /// MMU functions. ++ pub trait MMU { ++ /// Called by the kernel during early init. Supposed to take the translation tables from the ++ /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. ++ /// ++ /// # Safety ++ /// ++ /// - Changes the HW's global state. ++ unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; ++ ++ /// Returns true if the MMU is enabled, false otherwise. ++ fn is_enabled(&self) -> bool; ++ } ++} ++ ++/// Describes the characteristics of a translation granule. ++pub struct TranslationGranule; ++ ++/// Describes properties of an address space. ++pub struct AddressSpace; ++ ++/// Architecture agnostic translation types. ++#[allow(missing_docs)] ++#[allow(dead_code)] ++#[derive(Copy, Clone)] ++pub enum Translation { ++ Identity, ++ Offset(usize), ++} ++ ++/// Architecture agnostic memory attributes. ++#[allow(missing_docs)] ++#[derive(Copy, Clone)] ++pub enum MemAttributes { ++ CacheableDRAM, ++ Device, ++} ++ ++/// Architecture agnostic access permissions. ++#[allow(missing_docs)] ++#[derive(Copy, Clone)] ++pub enum AccessPermissions { ++ ReadOnly, ++ ReadWrite, ++} ++ ++/// Collection of memory attributes. ++#[allow(missing_docs)] ++#[derive(Copy, Clone)] ++pub struct AttributeFields { ++ pub mem_attributes: MemAttributes, ++ pub acc_perms: AccessPermissions, ++ pub execute_never: bool, ++} ++ ++/// Architecture agnostic descriptor for a memory range. ++#[allow(missing_docs)] ++pub struct TranslationDescriptor { ++ pub name: &'static str, ++ pub virtual_range: fn() -> RangeInclusive, ++ pub physical_range_translation: Translation, ++ pub attribute_fields: AttributeFields, ++} ++ ++/// Type for expressing the kernel's virtual memory layout. ++pub struct KernelVirtualLayout { ++ /// The last (inclusive) address of the address space. ++ max_virt_addr_inclusive: usize, ++ ++ /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. ++ inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl fmt::Display for MMUEnableError { ++ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ++ match self { ++ MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), ++ MMUEnableError::Other(x) => write!(f, "{}", x), ++ } ++ } ++} ++ ++impl TranslationGranule { ++ /// The granule's size. ++ pub const SIZE: usize = Self::size_checked(); ++ ++ /// The granule's shift, aka log2(size). ++ pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; ++ ++ const fn size_checked() -> usize { ++ assert!(GRANULE_SIZE.is_power_of_two()); ++ ++ GRANULE_SIZE ++ } ++} ++ ++impl AddressSpace { ++ /// The address space size. ++ pub const SIZE: usize = Self::size_checked(); ++ ++ /// The address space shift, aka log2(size). ++ pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; ++ ++ const fn size_checked() -> usize { ++ assert!(AS_SIZE.is_power_of_two()); ++ ++ // Check for architectural restrictions as well. ++ Self::arch_address_space_size_sanity_checks(); ++ ++ AS_SIZE ++ } ++} ++ ++impl Default for AttributeFields { ++ fn default() -> AttributeFields { ++ AttributeFields { ++ mem_attributes: MemAttributes::CacheableDRAM, ++ acc_perms: AccessPermissions::ReadWrite, ++ execute_never: true, ++ } ++ } ++} ++ ++/// Human-readable output of a TranslationDescriptor. ++impl fmt::Display for TranslationDescriptor { ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ // Call the function to which self.range points, and dereference the result, which causes ++ // Rust to copy the value. ++ let start = *(self.virtual_range)().start(); ++ let end = *(self.virtual_range)().end(); ++ let size = end - start + 1; ++ ++ let (size, unit) = common::size_human_readable_ceil(size); ++ ++ let attr = match self.attribute_fields.mem_attributes { ++ MemAttributes::CacheableDRAM => "C", ++ MemAttributes::Device => "Dev", ++ }; ++ ++ let acc_p = match self.attribute_fields.acc_perms { ++ AccessPermissions::ReadOnly => "RO", ++ AccessPermissions::ReadWrite => "RW", ++ }; ++ ++ let xn = if self.attribute_fields.execute_never { ++ "PXN" ++ } else { ++ "PX" ++ }; ++ ++ write!( ++ f, ++ " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", ++ start, end, size, unit, attr, acc_p, xn, self.name ++ ) ++ } ++} ++ ++impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { ++ /// Create a new instance. ++ pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { ++ Self { ++ max_virt_addr_inclusive: max, ++ inner: layout, ++ } ++ } ++ ++ /// For a virtual address, find and return the physical output address and corresponding ++ /// attributes. ++ /// ++ /// If the address is not found in `inner`, return an identity mapped default with normal ++ /// cacheable DRAM attributes. ++ pub fn virt_addr_properties( ++ &self, ++ virt_addr: usize, ++ ) -> Result<(usize, AttributeFields), &'static str> { ++ if virt_addr > self.max_virt_addr_inclusive { ++ return Err("Address out of range"); ++ } ++ ++ for i in self.inner.iter() { ++ if (i.virtual_range)().contains(&virt_addr) { ++ let output_addr = match i.physical_range_translation { ++ Translation::Identity => virt_addr, ++ Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), ++ }; ++ ++ return Ok((output_addr, i.attribute_fields)); ++ } ++ } ++ ++ Ok((virt_addr, AttributeFields::default())) ++ } ++ ++ /// Print the memory layout. ++ pub fn print_layout(&self) { ++ use crate::info; ++ ++ for i in self.inner.iter() { ++ info!("{}", i); ++ } ++ } ++} + +diff -uNr 09_privilege_level/src/memory.rs 10_virtual_mem_part1_identity_mapping/src/memory.rs +--- 09_privilege_level/src/memory.rs ++++ 10_virtual_mem_part1_identity_mapping/src/memory.rs +@@ -0,0 +1,7 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Memory Management. ++ ++pub mod mmu; + +``` diff --git a/10_virtual_mem_part1_identity_mapping/build.rs b/10_virtual_mem_part1_identity_mapping/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..602c9789c --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/boot.rs b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..c80f3ebbc --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(crate::kernel_init as *const () as u64); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} diff --git a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/boot.s b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..f6df21236 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. x0 holds the function argument provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..1051af6aa --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception/asynchronous.rs b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..65fcad25d --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..eea4465c4 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// # Safety +/// +/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". +static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + fn configure_translation_control(&self) { + let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI0::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG0::KiB_64 + + TCR_EL1::SH0::Inner + + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD0::EnableTTBR0Walks + + TCR_EL1::A1::TTBR0 + + TCR_EL1::T0SZ.val(t0sz) + + TCR_EL1::EPD1::DisableTTBR1Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Populate translation tables. + KERNEL_TABLES + .populate_tt_entries() + .map_err(MMUEnableError::Other)?; + + // Set the "Translation Table Base Register". + TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu/translation_table.rs b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..f3d8f6192 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, memory, + memory::mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn phys_start_addr_u64(&self) -> u64; + fn phys_start_addr_usize(&self) -> usize; +} + +const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], +} + +/// A translation table type for the kernel space. +pub type KernelTranslationTable = FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +// The binary is still identity mapped, so we don't need to convert here. +impl StartAddr for [T; N] { + fn phys_start_addr_u64(&self) -> u64 { + self as *const T as u64 + } + + fn phys_start_addr_usize(&self) -> usize { + self as *const _ as usize + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl FixedSizeTranslationTable { + /// Create an instance. + pub const fn new() -> Self { + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + } + } + + /// Iterates over all static translation table entries and fills them at once. + /// + /// # Safety + /// + /// - Modifies a `static mut`. Ensure it only happens from here. + pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { + for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { + *l2_entry = + TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); + + for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { + let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); + + let (phys_output_addr, attribute_fields) = + bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; + + *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); + } + } + + Ok(()) + } + + /// The translation table's base address to be used for programming the MMU. + pub fn phys_base_address(&self) -> u64 { + self.lvl2.phys_start_addr_u64() + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp.rs b/10_virtual_mem_part1_identity_mapping/src/bsp.rs new file mode 100644 index 000000000..7a3c804bd --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +pub mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs new file mode 100644 index 000000000..64049a4cf --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..1c343d1d7 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..8e57dfedb --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..d92612ea8 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/common.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..dfe7d8ef3 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..3ea864dc7 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..2a80ee2c5 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/kernel.ld b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..3ce16ccea --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2023 Andre Richter + */ + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..661476f4a --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | +//! | | +pub mod mmu; + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + /// The inclusive end address of the memory map. + /// + /// End address + 1 must be power of two. + /// + /// # Note + /// + /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for + /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. + /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. + /// + /// However, making this trade-off has the downside of making it possible for the CPU to assert a + /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on + /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. + pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0x4000_FFFF; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0xFF84_FFFF; + } +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_start() -> usize { + unsafe { __code_start.get() as usize } +} + +/// Exclusive end page address of the code segment. +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_end_exclusive() -> usize { + unsafe { __code_end_exclusive.get() as usize } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..6c2414f79 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use super::map as memory_map; +use crate::memory::mmu::*; +use core::ops::RangeInclusive; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The kernel's address space defined by this BSP. +pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; + +const NUM_MEM_RANGES: usize = 3; + +/// The virtual memory layout. +/// +/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. +/// It is agnostic of the paging granularity that the architecture's MMU will use. +pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( + memory_map::END_INCLUSIVE, + [ + TranslationDescriptor { + name: "Kernel code and RO data", + virtual_range: code_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadOnly, + execute_never: false, + }, + }, + TranslationDescriptor { + name: "Remapped Device MMIO", + virtual_range: remapped_mmio_range_inclusive, + physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + }, + TranslationDescriptor { + name: "Device MMIO", + virtual_range: mmio_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + }, + ], +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn code_range_inclusive() -> RangeInclusive { + // Notice the subtraction to turn the exclusive end into an inclusive end. + #[allow(clippy::range_minus_one)] + RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) +} + +fn remapped_mmio_range_inclusive() -> RangeInclusive { + // The last 64 KiB slot in the first 512 MiB + RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) +} + +fn mmio_range_inclusive() -> RangeInclusive { + RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the virtual memory layout. +pub fn virt_mem_layout() -> &'static KernelVirtualLayout { + &LAYOUT +} diff --git a/10_virtual_mem_part1_identity_mapping/src/common.rs b/10_virtual_mem_part1_identity_mapping/src/common.rs new file mode 100644 index 000000000..782a5da15 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/common.rs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/console.rs b/10_virtual_mem_part1_identity_mapping/src/console.rs new file mode 100644 index 000000000..a83f86fe0 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization::{self, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) +} diff --git a/10_virtual_mem_part1_identity_mapping/src/console/null_console.rs b/10_virtual_mem_part1_identity_mapping/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/10_virtual_mem_part1_identity_mapping/src/cpu.rs b/10_virtual_mem_part1_identity_mapping/src/cpu.rs new file mode 100644 index 000000000..67ab79c08 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/cpu.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; diff --git a/10_virtual_mem_part1_identity_mapping/src/cpu/boot.rs b/10_virtual_mem_part1_identity_mapping/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/10_virtual_mem_part1_identity_mapping/src/driver.rs b/10_virtual_mem_part1_identity_mapping/src/driver.rs new file mode 100644 index 000000000..050e7022f --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/driver.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + info, + synchronization::{interface::Mutex, NullLock}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/exception.rs b/10_virtual_mem_part1_identity_mapping/src/exception.rs new file mode 100644 index 000000000..45760391e --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/exception.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::current_privilege_level; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} diff --git a/10_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs b/10_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs new file mode 100644 index 000000000..fd059326e --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::print_state; diff --git a/10_virtual_mem_part1_identity_mapping/src/main.rs b/10_virtual_mem_part1_identity_mapping/src/main.rs new file mode 100644 index 000000000..52ce7d985 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/main.rs @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(int_roundings)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_main] +#![no_std] + +mod bsp; +mod common; +mod console; +mod cpu; +mod driver; +mod exception; +mod memory; +mod panic_wait; +mod print; +mod synchronization; +mod time; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order: +/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, +/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ +/// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + panic!("MMU: {}", string); + } + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + use console::{console, interface::Write}; + use core::time::Duration; + + info!( + "{} version {}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online. Special regions:"); + bsp::memory::mmu::virt_mem_layout().print_layout(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Timer test, spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); + + let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; + writeln!( + remapped_uart, + "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" + ) + .unwrap(); + + info!("Echoing input now"); + + // Discard any spurious received characters before going into echo mode. + console().clear_rx(); + loop { + let c = console().read_char(); + console().write_char(c); + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/memory.rs b/10_virtual_mem_part1_identity_mapping/src/memory.rs new file mode 100644 index 000000000..6dd8f186b --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/memory.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; diff --git a/10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs b/10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs new file mode 100644 index 000000000..87ed1efb2 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. +//! +//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file +//! provides types for composing an architecture-agnostic description of the kernel's virtual memory +//! layout. +//! +//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` +//! function. +//! +//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and +//! install respective translation tables. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod translation_table; + +use crate::common; +use core::{fmt, ops::RangeInclusive}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_mmu::mmu; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Called by the kernel during early init. Supposed to take the translation tables from the + /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Architecture agnostic translation types. +#[allow(missing_docs)] +#[allow(dead_code)] +#[derive(Copy, Clone)] +pub enum Translation { + Identity, + Offset(usize), +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// Architecture agnostic descriptor for a memory range. +#[allow(missing_docs)] +pub struct TranslationDescriptor { + pub name: &'static str, + pub virtual_range: fn() -> RangeInclusive, + pub physical_range_translation: Translation, + pub attribute_fields: AttributeFields, +} + +/// Type for expressing the kernel's virtual memory layout. +pub struct KernelVirtualLayout { + /// The last (inclusive) address of the address space. + max_virt_addr_inclusive: usize, + + /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. + inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +impl Default for AttributeFields { + fn default() -> AttributeFields { + AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + } + } +} + +/// Human-readable output of a TranslationDescriptor. +impl fmt::Display for TranslationDescriptor { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Call the function to which self.range points, and dereference the result, which causes + // Rust to copy the value. + let start = *(self.virtual_range)().start(); + let end = *(self.virtual_range)().end(); + let size = end - start + 1; + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match self.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match self.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if self.attribute_fields.execute_never { + "PXN" + } else { + "PX" + }; + + write!( + f, + " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", + start, end, size, unit, attr, acc_p, xn, self.name + ) + } +} + +impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { + /// Create a new instance. + pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { + Self { + max_virt_addr_inclusive: max, + inner: layout, + } + } + + /// For a virtual address, find and return the physical output address and corresponding + /// attributes. + /// + /// If the address is not found in `inner`, return an identity mapped default with normal + /// cacheable DRAM attributes. + pub fn virt_addr_properties( + &self, + virt_addr: usize, + ) -> Result<(usize, AttributeFields), &'static str> { + if virt_addr > self.max_virt_addr_inclusive { + return Err("Address out of range"); + } + + for i in self.inner.iter() { + if (i.virtual_range)().contains(&virt_addr) { + let output_addr = match i.physical_range_translation { + Translation::Identity => virt_addr, + Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), + }; + + return Ok((output_addr, i.attribute_fields)); + } + } + + Ok((virt_addr, AttributeFields::default())) + } + + /// Print the memory layout. + pub fn print_layout(&self) { + use crate::info; + + for i in self.inner.iter() { + info!("{}", i); + } + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/memory/mmu/translation_table.rs b/10_virtual_mem_part1_identity_mapping/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..1a2581aac --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/memory/mmu/translation_table.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_translation_table::KernelTranslationTable; diff --git a/10_virtual_mem_part1_identity_mapping/src/panic_wait.rs b/10_virtual_mem_part1_identity_mapping/src/panic_wait.rs new file mode 100644 index 000000000..5776aca87 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/panic_wait.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + cpu::wait_forever() +} diff --git a/10_virtual_mem_part1_identity_mapping/src/print.rs b/10_virtual_mem_part1_identity_mapping/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/10_virtual_mem_part1_identity_mapping/src/synchronization.rs b/10_virtual_mem_part1_identity_mapping/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/10_virtual_mem_part1_identity_mapping/src/time.rs b/10_virtual_mem_part1_identity_mapping/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/10_virtual_mem_part1_identity_mapping/tests/boot_test_string.rb b/10_virtual_mem_part1_identity_mapping/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/10_virtual_mem_part1_identity_mapping/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/11_exceptions_part1_groundwork/.vscode/settings.json b/11_exceptions_part1_groundwork/.vscode/settings.json new file mode 100644 index 000000000..bfa278e9a --- /dev/null +++ b/11_exceptions_part1_groundwork/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/11_exceptions_part1_groundwork/Cargo.lock b/11_exceptions_part1_groundwork/Cargo.lock new file mode 100644 index 000000000..dd741b8d0 --- /dev/null +++ b/11_exceptions_part1_groundwork/Cargo.lock @@ -0,0 +1,26 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.11.0" +dependencies = [ + "aarch64-cpu", + "tock-registers", +] + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/11_exceptions_part1_groundwork/Cargo.toml b/11_exceptions_part1_groundwork/Cargo.toml new file mode 100644 index 000000000..22343d4c5 --- /dev/null +++ b/11_exceptions_part1_groundwork/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "mingo" +version = "0.11.0" +authors = ["Andre Richter "] +edition = "2021" + +[profile.release] +lto = true + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] + +[[bin]] +name = "kernel" +path = "src/main.rs" + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff --git a/11_exceptions_part1_groundwork/Makefile b/11_exceptions_part1_groundwork/Makefile new file mode 100644 index 000000000..9549f0920 --- /dev/null +++ b/11_exceptions_part1_groundwork/Makefile @@ -0,0 +1,279 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/11_exceptions_part1_groundwork/README.md b/11_exceptions_part1_groundwork/README.md new file mode 100644 index 000000000..a9c9b3179 --- /dev/null +++ b/11_exceptions_part1_groundwork/README.md @@ -0,0 +1,1090 @@ +# Tutorial 11 - Exceptions Part 1: Groundwork + +## tl;dr + +- We lay the groundwork for all the architectural `CPU exceptions`. +- For now, only print an elaborate system state through a `panic!` call, and halt execution +- This will help finding bugs during development and runtime. +- For demo purposes, MMU `page faults` are used to demonstrate (i) returning from an exception and + (ii) the default `panic!` behavior. + +## Table of Contents + +- [Introduction](#introduction) +- [Exception Types](#exception-types) +- [Exception entry](#exception-entry) + * [Exception Vectors](#exception-vectors) +- [Handler Code and Offsets](#handler-code-and-offsets) +- [Rust and Assembly Implementation](#rust-and-assembly-implementation) + * [Context Save and Restore](#context-save-and-restore) + * [Exception Vector Table](#exception-vector-table) + * [Implementing handlers](#implementing-handlers) +- [Causing an Exception - Testing the Code](#causing-an-exception---testing-the-code) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +Now that we are executing in `EL1`, and have activated the `MMU`, time is due for implementing `CPU +exceptions`. For now, we only set up a scaffold with very basic functionality that will help us to +find bugs along the way. A follow-up `Interrupt` tutorial later will continue the work we start +here. + +Please note that this tutorial is specific to the `AArch64` architecture. It does not contain any +generic exception handling code yet. + +## Exception Types + +In `AArch64`, it is differentiated between four types of exceptions. These are: +- Synchronous + - For example, a `data abort` (e.g. `page fault`) or a `system call`. They happen in direct + consequence of executing a certain CPU instruction, hence _synchronously_. +- Interrupt Request (`IRQ`) + - For example, an external device, like a timer, is asserting a physical interrupt line. IRQs + happen _asynchronously_. +- Fast Interrupt Request (`FIQ`) + - These are basically interrupts that take priority over normal IRQs and have some more traits + that make them suitable to implement super-fast processing. However, this is out of scope for + this tutorial. For the sake of keeping these tutorials compact and concise, we will more or less + ignore FIQs and only implement a dummy handler that would halt the CPU core. +- System Error (`SError`) + - Like IRQs, SErrors happen asynchronously and are technically more or less the same. They are + intended to signal rather fatal errors in the system, e.g. if a transaction times out on the + `SoC` interconnect. They are very implementation specific and it is up to the SoC vendor to + decide which events are delivered as SErrors instead of normal IRQs. + +## Exception entry + +I recommend to read pages D1-5355 of the [ARMv8 Architecture Reference Manual][ARMv8_Manual Ja] to +understand the mechanisms of taking an exception. + +Here's an excerpt of important features for this tutorial: +- Exception entry moves the processor to the same or a higher `Exception Level`, but never to a + lower `EL`. +- The program status is saved in the `SPSR_ELx` register at the target `EL`. +- The preferred return address is saved in the `ELR_ELx` register. + - "Preferred" here means that `ELR_ELx` may hold the instruction address of the instructions that + caused the exception (`synchronous case`) or the first instruction that did not complete due to + an `asynchronous` exception. Details in pages D1-5357 of the [ARMv8 Architecture Reference + Manual][ARMv8_Manual Ja]. +- All kinds of exceptions are turned off upon taking an exception, so that by default, exception + handlers can not get interrupted themselves. +- Taking an exception will select the dedicated stack pointer of the target `EL`. + - For example, if an exception in `EL0` is taken, the Stack Pointer Select register `SPSel` will + switch from `0` to `1`, meaning that `SP_EL1` will be used by the exception vector code unless + you explicitly change it back to `SP_EL0`. + + +### Exception Vectors + +`AArch64` has a total of `16` exception vectors. There is one for each of the four kinds that were +introduced already, and additionally, it is taken into account _where_ the exception was taken from +and what the circumstances were. + +Here is a copy of the decision table as shown in pages D1-5358 of the [ARMv8 Architecture +Reference Manual][ARMv8_Manual Ja]: + +[ARMv8_Manual Ja]: https://developer.arm.com/documentation/ddi0487/ja/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Exception taken from Offset for exception type
SynchronousIRQ or vIRQFIQ or vFIQSError or vSError
Current Exception level with SP_EL0.0x0000x0800x1000x180
Current Exception level with SP_ELx, x>0.0x2000x2800x3000x380
Lower Exception level, where the implemented level immediately lower than the target level is using AArch64.0x4000x4800x5000x580
Lower Exception level, where the implemented level immediately lower than the target level is using AArch32.0x6000x6800x7000x780
+ +Since our kernel runs in `EL1`, using `SP_EL1`, if we'd cause a synchronous exception, the exception +vector at offset `0x200` would be executed. But what does that even mean? + +## Handler Code and Offsets + +In many architectures, Operating Systems register their exception handlers (aka vectors) by +compiling an architecturally defined data structure that stores function pointers to the different +handlers. This can be as simple as an ordinary array of function pointers. The `base address` of +this data structure is then stored into a special purpose register so that the CPU can branch to the +respective handler function upon taking an exception. The classic `x86_64` architecture follows this +principle, for example. + +In `AArch64`, it is a bit different. Here, we have the special purpose register as well, called +`VBAR_EL1`: Vector Base Address Register. + +However, it does not store the base address of an array of function pointers, but the base address +of a **memory location that contains code** for the 16 handlers, one handler back-to-back after the +other. Each handler can take a maximum space of `0x80` bytes, aka `128` bytes. That's why the table +above shows `offsets`: To indicate at which offset a certain handler starts. + +Of course, you are not obliged to cram all your handler code into only 128 bytes. You are free to +branch off to any other functions at any time. Actually, that is needed in most cases anyways, +because the context-saving code alone would take up most of the available space (you'll learn what +context saving is shortly). + +Additionally, there is a requirement that the `Vector Base Address` is aligned to `0x800` aka `2048` +bytes. + +## Rust and Assembly Implementation + +The implementation uses a mix of `Rust` and `Assembly` code. + +### Context Save and Restore + +Exception vectors, just like any other code, use a bunch of commonly shared processor resources. +Most of all, the set of `General Purpose Registers` (GPRs) that each core in `AArch64` provides +(`x0`-`x30`). + +In order to not taint these registers when executing exception vector code, it is general practice +to save these shared resources in memory (the stack, to be precise) as the very first action. This +is commonly described as *saving the context*. Exception vector code can then use the shared +resources in its own code without bothering, and as a last action before returning from exception +handling code, restore the context, so that the processor can continue where it left off before +taking the exception. + +Context save and restore is one of the few places in system software where there is no way around +some hand-crafted assembly. Introducing `exception.s`: + +```asm +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm +``` + +First, a macro for saving the context is defined. It eventually jumps to follow-up handler code, and +finally restores the context. In advance, we reserve space on the stack for the context. That is, +the 30 `GPRs`, the `link register`, the `exception link register` (holding the preferred return +address), the `saved program status` and the `exception syndrome register`. Afterwards, we store +those registers, save the current stack address in `x0` and branch off to follow-up handler-code, +whose function name is supplied as an argument to the macro (`\handler`). + +The handler code will be written in Rust, but use the platform's `C` ABI. This way, we can define a +function signature that has a pointer to the context-data on the stack as its first argument, and +know that this argument is expected to be in the `x0` register. We need to use the `C` ABI here +because `Rust` has no stable convention ([yet](https://github.com/rust-lang/rfcs/issues/600)). + +### Exception Vector Table + +Next, we craft the exception vector table: + +```asm +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +[...] +``` + +Note how each vector starts at the required offset from the section start using the `.org` +directive. Each macro call introduces an explicit handler function name, which is implemented in +`Rust` in `exception.rs`. + +### Implementing handlers + +The file `exception.rs` first defines a `struct` of the exception context that is stored on the +stack by the assembly code: + +```rust +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + // Exception syndrome register. + esr_el1: EsrEL1, +} +``` + +The handlers take a `struct ExceptionContext` argument. Since we do not plan to implement handlers +for each exception yet, a default handler is provided: + +```rust +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} +``` + +The actual handlers referenced from the assembly can now branch to it for the time being, e.g.: + +```rust +#[no_mangle] +extern "C" fn current_elx_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} +``` + +## Causing an Exception - Testing the Code + +We want to see two cases in action: +1. How taking, handling and returning from an exception works. +2. How the `panic!` print for unhandled exceptions looks like. + +So after setting up exceptions in `main.rs` by calling + +```rust +exception::handling_init(); +``` + +we cause a data abort exception by reading from memory address `8 GiB`: + +```rust +// Cause an exception by accessing a virtual address for which no translation was set up. This +// code accesses the address 8 GiB, which is outside the mapped address space. +// +// For demo purposes, the exception handler will catch the faulting 8 GiB address and allow +// execution to continue. +info!(""); +info!("Trying to read from address 8 GiB..."); +let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; +unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; +``` + +This triggers our exception code, because we try to read from a virtual address for which no mapping +has been installed. Remember, we only mapped up to `4 GiB` of address space in the previous +tutorial. + +To survive this exception, the respective handler has a special demo case: + +```rust +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + if e.fault_address_valid() { + let far_el1 = FAR_EL1.get(); + + // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, + // advance the exception link register for one instruction, so that execution can continue. + if far_el1 == 8 * 1024 * 1024 * 1024 { + e.elr_el1 += 4; + + return; + } + } + + default_exception_handler(e); +} +``` + +It checks if the faulting address equals `8 GiB`, and if so, advances the copy of the `ELR` by 4, +which makes it point to the next instruction after the instruction that caused the exception. When +this handler returns, execution continues in the assembly macro we introduced before. The macro has +only one more line left: `b __exception_restore_context`, which jumps to an assembly function that +plays back our saved context before finally executing `eret` to return from the exception. + +This will kick us back into `main.rs`. But we also want to see the `panic!` print. + +Therefore, a second read is done, this time from address `9 GiB`. A case which the handler will not +catch, eventually triggering the `panic!` call from the default handler. + +## Test it + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 64 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.798323] mingo version 0.11.0 +[ 0.798530] Booting on: Raspberry Pi 3 +[ 0.798985] MMU online. Special regions: +[ 0.799462] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data +[ 0.800480] 0x3f000000 - 0x4000ffff | 17 MiB | Dev RW PXN | Device MMIO +[ 0.801369] Current privilege level: EL1 +[ 0.801845] Exception handling state: +[ 0.802290] Debug: Masked +[ 0.802680] SError: Masked +[ 0.803069] IRQ: Masked +[ 0.803459] FIQ: Masked +[ 0.803849] Architectural timer resolution: 52 ns +[ 0.804423] Drivers loaded: +[ 0.804759] 1. BCM PL011 UART +[ 0.805182] 2. BCM GPIO +[ 0.805539] Timer test, spinning for 1 second +[ 1.806070] +[ 1.806074] Trying to read from address 8 GiB... +[ 1.806624] ************************************************ +[ 1.807316] Whoa! We recovered from a synchronous exception! +[ 1.808009] ************************************************ +[ 1.808703] +[ 1.808876] Let's try again +[ 1.809212] Trying to read from address 9 GiB... +[ 1.809776] Kernel panic! + +Panic location: + File 'src/_arch/aarch64/exception.rs', line 58, column 5 + +CPU Exception! + +ESR_EL1: 0x96000004 + Exception Class (EC) : 0x25 - Data Abort, current EL + Instr Specific Syndrome (ISS): 0x4 +FAR_EL1: 0x0000000240000000 +SPSR_EL1: 0x600003c5 + Flags: + Negative (N): Not set + Zero (Z): Set + Carry (C): Set + Overflow (V): Not set + Exception handling state: + Debug (D): Masked + SError (A): Masked + IRQ (I): Masked + FIQ (F): Masked + Illegal Execution State (IL): Not set +ELR_EL1: 0x00000000000845f8 + +General purpose register: + x0 : 0x0000000000000000 x1 : 0x0000000000086187 + x2 : 0x0000000000000027 x3 : 0x0000000000081280 + x4 : 0x0000000000000006 x5 : 0x1e27329c00000000 + x6 : 0x0000000000000000 x7 : 0xd3d18908028f0243 + x8 : 0x0000000240000000 x9 : 0x0000000000086187 + x10: 0x0000000000000443 x11: 0x000000003f201000 + x12: 0x0000000000000019 x13: 0x00000000ffffd8f0 + x14: 0x000000000000147b x15: 0x00000000ffffff9c + x16: 0x000000000007fd38 x17: 0x0000000005f5e0ff + x18: 0x00000000000c58fc x19: 0x0000000000090008 + x20: 0x0000000000085fc0 x21: 0x000000003b9aca00 + x22: 0x0000000000082238 x23: 0x00000000000813d4 + x24: 0x0000000010624dd3 x25: 0xffffffffc4653600 + x26: 0x0000000000086988 x27: 0x0000000000086080 + x28: 0x0000000000085f10 x29: 0x0000000000085c00 + lr : 0x00000000000845ec +``` + +## Diff to previous +```diff + +diff -uNr 10_virtual_mem_part1_identity_mapping/Cargo.toml 11_exceptions_part1_groundwork/Cargo.toml +--- 10_virtual_mem_part1_identity_mapping/Cargo.toml ++++ 11_exceptions_part1_groundwork/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.10.0" ++version = "0.11.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs +--- 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs ++++ 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs +@@ -11,8 +11,263 @@ + //! + //! crate::exception::arch_exception + +-use aarch64_cpu::registers::*; +-use tock_registers::interfaces::Readable; ++use aarch64_cpu::{asm::barrier, registers::*}; ++use core::{arch::global_asm, cell::UnsafeCell, fmt}; ++use tock_registers::{ ++ interfaces::{Readable, Writeable}, ++ registers::InMemoryRegister, ++}; ++ ++// Assembly counterpart to this file. ++global_asm!(include_str!("exception.s")); ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Wrapper structs for memory copies of registers. ++#[repr(transparent)] ++struct SpsrEL1(InMemoryRegister); ++struct EsrEL1(InMemoryRegister); ++ ++/// The exception context as it is stored on the stack on exception entry. ++#[repr(C)] ++struct ExceptionContext { ++ /// General Purpose Registers. ++ gpr: [u64; 30], ++ ++ /// The link register, aka x30. ++ lr: u64, ++ ++ /// Exception link register. The program counter at the time the exception happened. ++ elr_el1: u64, ++ ++ /// Saved program status. ++ spsr_el1: SpsrEL1, ++ ++ /// Exception syndrome register. ++ esr_el1: EsrEL1, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Prints verbose information about the exception and then panics. ++fn default_exception_handler(exc: &ExceptionContext) { ++ panic!( ++ "CPU Exception!\n\n\ ++ {}", ++ exc ++ ); ++} ++ ++//------------------------------------------------------------------------------ ++// Current, EL0 ++//------------------------------------------------------------------------------ ++ ++#[no_mangle] ++extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { ++ panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") ++} ++ ++#[no_mangle] ++extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { ++ panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") ++} ++ ++#[no_mangle] ++extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { ++ panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") ++} ++ ++//------------------------------------------------------------------------------ ++// Current, ELx ++//------------------------------------------------------------------------------ ++ ++#[no_mangle] ++extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { ++ if e.fault_address_valid() { ++ let far_el1 = FAR_EL1.get(); ++ ++ // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, ++ // advance the exception link register for one instruction, so that execution can continue. ++ if far_el1 == 8 * 1024 * 1024 * 1024 { ++ e.elr_el1 += 4; ++ ++ return; ++ } ++ } ++ ++ default_exception_handler(e); ++} ++ ++#[no_mangle] ++extern "C" fn current_elx_irq(e: &mut ExceptionContext) { ++ default_exception_handler(e); ++} ++ ++#[no_mangle] ++extern "C" fn current_elx_serror(e: &mut ExceptionContext) { ++ default_exception_handler(e); ++} ++ ++//------------------------------------------------------------------------------ ++// Lower, AArch64 ++//------------------------------------------------------------------------------ ++ ++#[no_mangle] ++extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { ++ default_exception_handler(e); ++} ++ ++#[no_mangle] ++extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { ++ default_exception_handler(e); ++} ++ ++#[no_mangle] ++extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { ++ default_exception_handler(e); ++} ++ ++//------------------------------------------------------------------------------ ++// Lower, AArch32 ++//------------------------------------------------------------------------------ ++ ++#[no_mangle] ++extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { ++ default_exception_handler(e); ++} ++ ++#[no_mangle] ++extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { ++ default_exception_handler(e); ++} ++ ++#[no_mangle] ++extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { ++ default_exception_handler(e); ++} ++ ++//------------------------------------------------------------------------------ ++// Misc ++//------------------------------------------------------------------------------ ++ ++/// Human readable SPSR_EL1. ++#[rustfmt::skip] ++impl fmt::Display for SpsrEL1 { ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ // Raw value. ++ writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; ++ ++ let to_flag_str = |x| -> _ { ++ if x { "Set" } else { "Not set" } ++ }; ++ ++ writeln!(f, " Flags:")?; ++ writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; ++ writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; ++ writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; ++ writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; ++ ++ let to_mask_str = |x| -> _ { ++ if x { "Masked" } else { "Unmasked" } ++ }; ++ ++ writeln!(f, " Exception handling state:")?; ++ writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; ++ writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; ++ writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; ++ writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; ++ ++ write!(f, " Illegal Execution State (IL): {}", ++ to_flag_str(self.0.is_set(SPSR_EL1::IL)) ++ ) ++ } ++} ++ ++impl EsrEL1 { ++ #[inline(always)] ++ fn exception_class(&self) -> Option { ++ self.0.read_as_enum(ESR_EL1::EC) ++ } ++} ++ ++/// Human readable ESR_EL1. ++#[rustfmt::skip] ++impl fmt::Display for EsrEL1 { ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ // Raw print of whole register. ++ writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; ++ ++ // Raw print of exception class. ++ write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; ++ ++ // Exception class. ++ let ec_translation = match self.exception_class() { ++ Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", ++ _ => "N/A", ++ }; ++ writeln!(f, " - {}", ec_translation)?; ++ ++ // Raw print of instruction specific syndrome. ++ write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) ++ } ++} ++ ++impl ExceptionContext { ++ #[inline(always)] ++ fn exception_class(&self) -> Option { ++ self.esr_el1.exception_class() ++ } ++ ++ #[inline(always)] ++ fn fault_address_valid(&self) -> bool { ++ use ESR_EL1::EC::Value::*; ++ ++ match self.exception_class() { ++ None => false, ++ Some(ec) => matches!( ++ ec, ++ InstrAbortLowerEL ++ | InstrAbortCurrentEL ++ | PCAlignmentFault ++ | DataAbortLowerEL ++ | DataAbortCurrentEL ++ | WatchpointLowerEL ++ | WatchpointCurrentEL ++ ), ++ } ++ } ++} ++ ++/// Human readable print of the exception context. ++impl fmt::Display for ExceptionContext { ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ writeln!(f, "{}", self.esr_el1)?; ++ ++ if self.fault_address_valid() { ++ writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; ++ } ++ ++ writeln!(f, "{}", self.spsr_el1)?; ++ writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; ++ writeln!(f)?; ++ writeln!(f, "General purpose register:")?; ++ ++ #[rustfmt::skip] ++ let alternating = |x| -> _ { ++ if x modulo 2 == 0 { " " } else { "\n" } ++ }; ++ ++ // Print two registers per line. ++ for (i, reg) in self.gpr.iter().enumerate() { ++ write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; ++ } ++ write!(f, " lr : {:#018x}", self.lr) ++ } ++} + + //-------------------------------------------------------------------------------------------------- + // Public Code +@@ -29,3 +284,23 @@ + _ => (PrivilegeLevel::Unknown, "Unknown"), + } + } ++ ++/// Init exception handling by setting the exception vector base address register. ++/// ++/// # Safety ++/// ++/// - Changes the HW state of the executing core. ++/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must ++/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference ++/// Manual. ++pub unsafe fn handling_init() { ++ // Provided by exception.S. ++ extern "Rust" { ++ static __exception_vector_start: UnsafeCell<()>; ++ } ++ ++ VBAR_EL1.set(__exception_vector_start.get() as u64); ++ ++ // Force VBAR update to complete before next instruction. ++ barrier::isb(barrier::SY); ++} + +diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.s 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s +--- 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.s ++++ 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s +@@ -0,0 +1,154 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//-------------------------------------------------------------------------------------------------- ++// Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Call the function provided by parameter `\handler` after saving the exception context. Provide ++/// the context as the first parameter to '\handler'. ++.macro CALL_WITH_CONTEXT handler ++__vector_\handler: ++ // Make room on the stack for the exception context. ++ sub sp, sp, #16 * 17 ++ ++ // Store all general purpose registers on the stack. ++ stp x0, x1, [sp, #16 * 0] ++ stp x2, x3, [sp, #16 * 1] ++ stp x4, x5, [sp, #16 * 2] ++ stp x6, x7, [sp, #16 * 3] ++ stp x8, x9, [sp, #16 * 4] ++ stp x10, x11, [sp, #16 * 5] ++ stp x12, x13, [sp, #16 * 6] ++ stp x14, x15, [sp, #16 * 7] ++ stp x16, x17, [sp, #16 * 8] ++ stp x18, x19, [sp, #16 * 9] ++ stp x20, x21, [sp, #16 * 10] ++ stp x22, x23, [sp, #16 * 11] ++ stp x24, x25, [sp, #16 * 12] ++ stp x26, x27, [sp, #16 * 13] ++ stp x28, x29, [sp, #16 * 14] ++ ++ // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception ++ // syndrome register (ESR_EL1). ++ mrs x1, ELR_EL1 ++ mrs x2, SPSR_EL1 ++ mrs x3, ESR_EL1 ++ ++ stp lr, x1, [sp, #16 * 15] ++ stp x2, x3, [sp, #16 * 16] ++ ++ // x0 is the first argument for the function called through `\handler`. ++ mov x0, sp ++ ++ // Call `\handler`. ++ bl \handler ++ ++ // After returning from exception handling code, replay the saved context and return via ++ // `eret`. ++ b __exception_restore_context ++ ++.size __vector_\handler, . - __vector_\handler ++.type __vector_\handler, function ++.endm ++ ++.macro FIQ_SUSPEND ++1: wfe ++ b 1b ++.endm ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++.section .text ++ ++//------------------------------------------------------------------------------ ++// The exception vector table. ++//------------------------------------------------------------------------------ ++ ++// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. ++.align 11 ++ ++// Export a symbol for the Rust code to use. ++__exception_vector_start: ++ ++// Current exception level with SP_EL0. ++// ++// .org sets the offset relative to section start. ++// ++// # Safety ++// ++// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. ++.org 0x000 ++ CALL_WITH_CONTEXT current_el0_synchronous ++.org 0x080 ++ CALL_WITH_CONTEXT current_el0_irq ++.org 0x100 ++ FIQ_SUSPEND ++.org 0x180 ++ CALL_WITH_CONTEXT current_el0_serror ++ ++// Current exception level with SP_ELx, x > 0. ++.org 0x200 ++ CALL_WITH_CONTEXT current_elx_synchronous ++.org 0x280 ++ CALL_WITH_CONTEXT current_elx_irq ++.org 0x300 ++ FIQ_SUSPEND ++.org 0x380 ++ CALL_WITH_CONTEXT current_elx_serror ++ ++// Lower exception level, AArch64 ++.org 0x400 ++ CALL_WITH_CONTEXT lower_aarch64_synchronous ++.org 0x480 ++ CALL_WITH_CONTEXT lower_aarch64_irq ++.org 0x500 ++ FIQ_SUSPEND ++.org 0x580 ++ CALL_WITH_CONTEXT lower_aarch64_serror ++ ++// Lower exception level, AArch32 ++.org 0x600 ++ CALL_WITH_CONTEXT lower_aarch32_synchronous ++.org 0x680 ++ CALL_WITH_CONTEXT lower_aarch32_irq ++.org 0x700 ++ FIQ_SUSPEND ++.org 0x780 ++ CALL_WITH_CONTEXT lower_aarch32_serror ++.org 0x800 ++ ++//------------------------------------------------------------------------------ ++// fn __exception_restore_context() ++//------------------------------------------------------------------------------ ++__exception_restore_context: ++ ldr w19, [sp, #16 * 16] ++ ldp lr, x20, [sp, #16 * 15] ++ ++ msr SPSR_EL1, x19 ++ msr ELR_EL1, x20 ++ ++ ldp x0, x1, [sp, #16 * 0] ++ ldp x2, x3, [sp, #16 * 1] ++ ldp x4, x5, [sp, #16 * 2] ++ ldp x6, x7, [sp, #16 * 3] ++ ldp x8, x9, [sp, #16 * 4] ++ ldp x10, x11, [sp, #16 * 5] ++ ldp x12, x13, [sp, #16 * 6] ++ ldp x14, x15, [sp, #16 * 7] ++ ldp x16, x17, [sp, #16 * 8] ++ ldp x18, x19, [sp, #16 * 9] ++ ldp x20, x21, [sp, #16 * 10] ++ ldp x22, x23, [sp, #16 * 11] ++ ldp x24, x25, [sp, #16 * 12] ++ ldp x26, x27, [sp, #16 * 13] ++ ldp x28, x29, [sp, #16 * 14] ++ ++ add sp, sp, #16 * 17 ++ ++ eret ++ ++.size __exception_restore_context, . - __exception_restore_context ++.type __exception_restore_context, function + +diff -uNr 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs 11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs +--- 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs ++++ 11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs +@@ -15,7 +15,7 @@ + /// The kernel's address space defined by this BSP. + pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; + +-const NUM_MEM_RANGES: usize = 3; ++const NUM_MEM_RANGES: usize = 2; + + /// The virtual memory layout. + /// +@@ -35,16 +35,6 @@ + }, + }, + TranslationDescriptor { +- name: "Remapped Device MMIO", +- virtual_range: remapped_mmio_range_inclusive, +- physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), +- attribute_fields: AttributeFields { +- mem_attributes: MemAttributes::Device, +- acc_perms: AccessPermissions::ReadWrite, +- execute_never: true, +- }, +- }, +- TranslationDescriptor { + name: "Device MMIO", + virtual_range: mmio_range_inclusive, + physical_range_translation: Translation::Identity, +@@ -67,11 +57,6 @@ + RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) + } + +-fn remapped_mmio_range_inclusive() -> RangeInclusive { +- // The last 64 KiB slot in the first 512 MiB +- RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) +-} +- + fn mmio_range_inclusive() -> RangeInclusive { + RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) + } + +diff -uNr 10_virtual_mem_part1_identity_mapping/src/bsp.rs 11_exceptions_part1_groundwork/src/bsp.rs +--- 10_virtual_mem_part1_identity_mapping/src/bsp.rs ++++ 11_exceptions_part1_groundwork/src/bsp.rs +@@ -4,7 +4,7 @@ + + //! Conditional reexporting of Board Support Packages. + +-pub mod device_driver; ++mod device_driver; + + #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] + mod raspberrypi; + +diff -uNr 10_virtual_mem_part1_identity_mapping/src/exception.rs 11_exceptions_part1_groundwork/src/exception.rs +--- 10_virtual_mem_part1_identity_mapping/src/exception.rs ++++ 11_exceptions_part1_groundwork/src/exception.rs +@@ -13,7 +13,7 @@ + //-------------------------------------------------------------------------------------------------- + // Architectural Public Reexports + //-------------------------------------------------------------------------------------------------- +-pub use arch_exception::current_privilege_level; ++pub use arch_exception::{current_privilege_level, handling_init}; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions + +diff -uNr 10_virtual_mem_part1_identity_mapping/src/main.rs 11_exceptions_part1_groundwork/src/main.rs +--- 10_virtual_mem_part1_identity_mapping/src/main.rs ++++ 11_exceptions_part1_groundwork/src/main.rs +@@ -144,6 +144,8 @@ + unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + ++ exception::handling_init(); ++ + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + panic!("MMU: {}", string); + } +@@ -163,7 +165,7 @@ + + /// The main function running after the early init. + fn kernel_main() -> ! { +- use console::{console, interface::Write}; ++ use console::console; + use core::time::Duration; + + info!( +@@ -193,13 +195,28 @@ + info!("Timer test, spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); + +- let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; +- writeln!( +- remapped_uart, +- "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" +- ) +- .unwrap(); ++ // Cause an exception by accessing a virtual address for which no translation was set up. This ++ // code accesses the address 8 GiB, which is outside the mapped address space. ++ // ++ // For demo purposes, the exception handler will catch the faulting 8 GiB address and allow ++ // execution to continue. ++ info!(""); ++ info!("Trying to read from address 8 GiB..."); ++ let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; ++ unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; ++ ++ info!("************************************************"); ++ info!("Whoa! We recovered from a synchronous exception!"); ++ info!("************************************************"); ++ info!(""); ++ info!("Let's try again"); ++ ++ // Now use address 9 GiB. The exception handler won't forgive us this time. ++ info!("Trying to read from address 9 GiB..."); ++ big_addr = 9 * 1024 * 1024 * 1024; ++ unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; + ++ // Will never reach here in this tutorial. + info!("Echoing input now"); + + // Discard any spurious received characters before going into echo mode. + +diff -uNr 10_virtual_mem_part1_identity_mapping/tests/boot_test_string.rb 11_exceptions_part1_groundwork/tests/boot_test_string.rb +--- 10_virtual_mem_part1_identity_mapping/tests/boot_test_string.rb ++++ 11_exceptions_part1_groundwork/tests/boot_test_string.rb +@@ -1,3 +1,3 @@ + # frozen_string_literal: true + +-EXPECTED_PRINT = 'Echoing input now' ++EXPECTED_PRINT = 'lr : 0x' + +``` diff --git a/11_exceptions_part1_groundwork/build.rs b/11_exceptions_part1_groundwork/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/11_exceptions_part1_groundwork/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..602c9789c --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..c80f3ebbc --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(crate::kernel_init as *const () as u64); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.s b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..f6df21236 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. x0 holds the function argument provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..9d2ed5b76 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!(include_str!("exception.s")); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + if e.fault_address_valid() { + let far_el1 = FAR_EL1.get(); + + // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, + // advance the exception link register for one instruction, so that execution can continue. + if far_el1 == 8 * 1024 * 1024 * 1024 { + e.elr_el1 += 4; + + return; + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..91805ee7c --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 17 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..65fcad25d --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..eea4465c4 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// # Safety +/// +/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". +static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + fn configure_translation_control(&self) { + let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI0::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG0::KiB_64 + + TCR_EL1::SH0::Inner + + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD0::EnableTTBR0Walks + + TCR_EL1::A1::TTBR0 + + TCR_EL1::T0SZ.val(t0sz) + + TCR_EL1::EPD1::DisableTTBR1Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Populate translation tables. + KERNEL_TABLES + .populate_tt_entries() + .map_err(MMUEnableError::Other)?; + + // Set the "Translation Table Base Register". + TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu/translation_table.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..f3d8f6192 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, memory, + memory::mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn phys_start_addr_u64(&self) -> u64; + fn phys_start_addr_usize(&self) -> usize; +} + +const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], +} + +/// A translation table type for the kernel space. +pub type KernelTranslationTable = FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +// The binary is still identity mapped, so we don't need to convert here. +impl StartAddr for [T; N] { + fn phys_start_addr_u64(&self) -> u64 { + self as *const T as u64 + } + + fn phys_start_addr_usize(&self) -> usize { + self as *const _ as usize + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl FixedSizeTranslationTable { + /// Create an instance. + pub const fn new() -> Self { + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + } + } + + /// Iterates over all static translation table entries and fills them at once. + /// + /// # Safety + /// + /// - Modifies a `static mut`. Ensure it only happens from here. + pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { + for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { + *l2_entry = + TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); + + for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { + let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); + + let (phys_output_addr, attribute_fields) = + bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; + + *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); + } + } + + Ok(()) + } + + /// The translation table's base address to be used for programming the MMU. + pub fn phys_base_address(&self) -> u64 { + self.lvl2.phys_start_addr_u64() + } +} diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/time.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/11_exceptions_part1_groundwork/src/bsp.rs b/11_exceptions_part1_groundwork/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/11_exceptions_part1_groundwork/src/bsp/device_driver.rs b/11_exceptions_part1_groundwork/src/bsp/device_driver.rs new file mode 100644 index 000000000..64049a4cf --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs b/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..1c343d1d7 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..8e57dfedb --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..d92612ea8 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff --git a/11_exceptions_part1_groundwork/src/bsp/device_driver/common.rs b/11_exceptions_part1_groundwork/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..dfe7d8ef3 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..3ea864dc7 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..2a80ee2c5 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/kernel.ld b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..6d939889b --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..661476f4a --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | +//! | | +pub mod mmu; + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + /// The inclusive end address of the memory map. + /// + /// End address + 1 must be power of two. + /// + /// # Note + /// + /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for + /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. + /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. + /// + /// However, making this trade-off has the downside of making it possible for the CPU to assert a + /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on + /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. + pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0x4000_FFFF; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0xFF84_FFFF; + } +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_start() -> usize { + unsafe { __code_start.get() as usize } +} + +/// Exclusive end page address of the code segment. +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_end_exclusive() -> usize { + unsafe { __code_end_exclusive.get() as usize } +} diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..6009ace48 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use super::map as memory_map; +use crate::memory::mmu::*; +use core::ops::RangeInclusive; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The kernel's address space defined by this BSP. +pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; + +const NUM_MEM_RANGES: usize = 2; + +/// The virtual memory layout. +/// +/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. +/// It is agnostic of the paging granularity that the architecture's MMU will use. +pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( + memory_map::END_INCLUSIVE, + [ + TranslationDescriptor { + name: "Kernel code and RO data", + virtual_range: code_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadOnly, + execute_never: false, + }, + }, + TranslationDescriptor { + name: "Device MMIO", + virtual_range: mmio_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + }, + ], +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn code_range_inclusive() -> RangeInclusive { + // Notice the subtraction to turn the exclusive end into an inclusive end. + #[allow(clippy::range_minus_one)] + RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) +} + +fn mmio_range_inclusive() -> RangeInclusive { + RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the virtual memory layout. +pub fn virt_mem_layout() -> &'static KernelVirtualLayout { + &LAYOUT +} diff --git a/11_exceptions_part1_groundwork/src/common.rs b/11_exceptions_part1_groundwork/src/common.rs new file mode 100644 index 000000000..782a5da15 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/common.rs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/11_exceptions_part1_groundwork/src/console.rs b/11_exceptions_part1_groundwork/src/console.rs new file mode 100644 index 000000000..a83f86fe0 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization::{self, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) +} diff --git a/11_exceptions_part1_groundwork/src/console/null_console.rs b/11_exceptions_part1_groundwork/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/11_exceptions_part1_groundwork/src/cpu.rs b/11_exceptions_part1_groundwork/src/cpu.rs new file mode 100644 index 000000000..67ab79c08 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/cpu.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; diff --git a/11_exceptions_part1_groundwork/src/cpu/boot.rs b/11_exceptions_part1_groundwork/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/11_exceptions_part1_groundwork/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/11_exceptions_part1_groundwork/src/driver.rs b/11_exceptions_part1_groundwork/src/driver.rs new file mode 100644 index 000000000..050e7022f --- /dev/null +++ b/11_exceptions_part1_groundwork/src/driver.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + info, + synchronization::{interface::Mutex, NullLock}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/11_exceptions_part1_groundwork/src/exception.rs b/11_exceptions_part1_groundwork/src/exception.rs new file mode 100644 index 000000000..77b582482 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/exception.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} diff --git a/11_exceptions_part1_groundwork/src/exception/asynchronous.rs b/11_exceptions_part1_groundwork/src/exception/asynchronous.rs new file mode 100644 index 000000000..fd059326e --- /dev/null +++ b/11_exceptions_part1_groundwork/src/exception/asynchronous.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::print_state; diff --git a/11_exceptions_part1_groundwork/src/main.rs b/11_exceptions_part1_groundwork/src/main.rs new file mode 100644 index 000000000..fc01bb3b9 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/main.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(int_roundings)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_main] +#![no_std] + +mod bsp; +mod common; +mod console; +mod cpu; +mod driver; +mod exception; +mod memory; +mod panic_wait; +mod print; +mod synchronization; +mod time; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order: +/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, +/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ +/// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + exception::handling_init(); + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + panic!("MMU: {}", string); + } + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + use console::console; + use core::time::Duration; + + info!( + "{} version {}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online. Special regions:"); + bsp::memory::mmu::virt_mem_layout().print_layout(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Timer test, spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); + + // Cause an exception by accessing a virtual address for which no translation was set up. This + // code accesses the address 8 GiB, which is outside the mapped address space. + // + // For demo purposes, the exception handler will catch the faulting 8 GiB address and allow + // execution to continue. + info!(""); + info!("Trying to read from address 8 GiB..."); + let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; + unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; + + info!("************************************************"); + info!("Whoa! We recovered from a synchronous exception!"); + info!("************************************************"); + info!(""); + info!("Let's try again"); + + // Now use address 9 GiB. The exception handler won't forgive us this time. + info!("Trying to read from address 9 GiB..."); + big_addr = 9 * 1024 * 1024 * 1024; + unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; + + // Will never reach here in this tutorial. + info!("Echoing input now"); + + // Discard any spurious received characters before going into echo mode. + console().clear_rx(); + loop { + let c = console().read_char(); + console().write_char(c); + } +} diff --git a/11_exceptions_part1_groundwork/src/memory.rs b/11_exceptions_part1_groundwork/src/memory.rs new file mode 100644 index 000000000..6dd8f186b --- /dev/null +++ b/11_exceptions_part1_groundwork/src/memory.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; diff --git a/11_exceptions_part1_groundwork/src/memory/mmu.rs b/11_exceptions_part1_groundwork/src/memory/mmu.rs new file mode 100644 index 000000000..87ed1efb2 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/memory/mmu.rs @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. +//! +//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file +//! provides types for composing an architecture-agnostic description of the kernel's virtual memory +//! layout. +//! +//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` +//! function. +//! +//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and +//! install respective translation tables. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod translation_table; + +use crate::common; +use core::{fmt, ops::RangeInclusive}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_mmu::mmu; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Called by the kernel during early init. Supposed to take the translation tables from the + /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Architecture agnostic translation types. +#[allow(missing_docs)] +#[allow(dead_code)] +#[derive(Copy, Clone)] +pub enum Translation { + Identity, + Offset(usize), +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// Architecture agnostic descriptor for a memory range. +#[allow(missing_docs)] +pub struct TranslationDescriptor { + pub name: &'static str, + pub virtual_range: fn() -> RangeInclusive, + pub physical_range_translation: Translation, + pub attribute_fields: AttributeFields, +} + +/// Type for expressing the kernel's virtual memory layout. +pub struct KernelVirtualLayout { + /// The last (inclusive) address of the address space. + max_virt_addr_inclusive: usize, + + /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. + inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +impl Default for AttributeFields { + fn default() -> AttributeFields { + AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + } + } +} + +/// Human-readable output of a TranslationDescriptor. +impl fmt::Display for TranslationDescriptor { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Call the function to which self.range points, and dereference the result, which causes + // Rust to copy the value. + let start = *(self.virtual_range)().start(); + let end = *(self.virtual_range)().end(); + let size = end - start + 1; + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match self.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match self.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if self.attribute_fields.execute_never { + "PXN" + } else { + "PX" + }; + + write!( + f, + " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", + start, end, size, unit, attr, acc_p, xn, self.name + ) + } +} + +impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { + /// Create a new instance. + pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { + Self { + max_virt_addr_inclusive: max, + inner: layout, + } + } + + /// For a virtual address, find and return the physical output address and corresponding + /// attributes. + /// + /// If the address is not found in `inner`, return an identity mapped default with normal + /// cacheable DRAM attributes. + pub fn virt_addr_properties( + &self, + virt_addr: usize, + ) -> Result<(usize, AttributeFields), &'static str> { + if virt_addr > self.max_virt_addr_inclusive { + return Err("Address out of range"); + } + + for i in self.inner.iter() { + if (i.virtual_range)().contains(&virt_addr) { + let output_addr = match i.physical_range_translation { + Translation::Identity => virt_addr, + Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), + }; + + return Ok((output_addr, i.attribute_fields)); + } + } + + Ok((virt_addr, AttributeFields::default())) + } + + /// Print the memory layout. + pub fn print_layout(&self) { + use crate::info; + + for i in self.inner.iter() { + info!("{}", i); + } + } +} diff --git a/11_exceptions_part1_groundwork/src/memory/mmu/translation_table.rs b/11_exceptions_part1_groundwork/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..1a2581aac --- /dev/null +++ b/11_exceptions_part1_groundwork/src/memory/mmu/translation_table.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_translation_table::KernelTranslationTable; diff --git a/11_exceptions_part1_groundwork/src/panic_wait.rs b/11_exceptions_part1_groundwork/src/panic_wait.rs new file mode 100644 index 000000000..5776aca87 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/panic_wait.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + cpu::wait_forever() +} diff --git a/11_exceptions_part1_groundwork/src/print.rs b/11_exceptions_part1_groundwork/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/11_exceptions_part1_groundwork/src/synchronization.rs b/11_exceptions_part1_groundwork/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/11_exceptions_part1_groundwork/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/11_exceptions_part1_groundwork/src/time.rs b/11_exceptions_part1_groundwork/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/11_exceptions_part1_groundwork/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/11_exceptions_part1_groundwork/tests/boot_test_string.rb b/11_exceptions_part1_groundwork/tests/boot_test_string.rb new file mode 100644 index 000000000..200cd9713 --- /dev/null +++ b/11_exceptions_part1_groundwork/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'lr : 0x' diff --git a/11_virtual_mem_part1_identity_mapping/.vscode/settings.json b/11_virtual_mem_part1_identity_mapping/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/11_virtual_mem_part1_identity_mapping/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/11_virtual_mem_part1_identity_mapping/Cargo.lock b/11_virtual_mem_part1_identity_mapping/Cargo.lock deleted file mode 100644 index 7b2456e16..000000000 --- a/11_virtual_mem_part1_identity_mapping/Cargo.lock +++ /dev/null @@ -1,33 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "register", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/11_virtual_mem_part1_identity_mapping/Cargo.toml b/11_virtual_mem_part1_identity_mapping/Cargo.toml deleted file mode 100644 index b8906da1f..000000000 --- a/11_virtual_mem_part1_identity_mapping/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Optional dependencies -register = { version = "1.x.x", optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/11_virtual_mem_part1_identity_mapping/Makefile b/11_virtual_mem_part1_identity_mapping/Makefile deleted file mode 100644 index 5f49b1af5..000000000 --- a/11_virtual_mem_part1_identity_mapping/Makefile +++ /dev/null @@ -1,146 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot -DOCKER_ARG_DEV = --privileged -v /dev:/dev -DOCKER_ARG_NET = --network host - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) - DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) - DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -else - DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot jtagboot openocd gdb gdb-opt0 clippy \ - clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -endif - -chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -jtagboot: - @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) - -openocd: - @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) - -define gen_gdb - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC) $1" $(RUSTC_CMD) - @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) -endef - -gdb: - $(call gen_gdb,-C debuginfo=2) - -gdb-opt0: - $(call gen_gdb,-C debuginfo=2 -C opt-level=0) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/11_virtual_mem_part1_identity_mapping/README.md b/11_virtual_mem_part1_identity_mapping/README.md deleted file mode 100644 index 4d9299a27..000000000 --- a/11_virtual_mem_part1_identity_mapping/README.md +++ /dev/null @@ -1,1131 +0,0 @@ -# Tutorial 11 - Virtual Memory Part 1: Identity Map All The Things! - -## tl;dr - -- The `MMU` is turned on. -- A simple scheme is used: static `64 KiB` translation tables. -- For educational purposes, we write to a remapped `UART`, and `identity map` everything else. - -## Table of Contents - -- [Introduction](#introduction) -- [MMU and paging theory](#mmu-and-paging-theory) -- [Approach](#approach) - * [Generic Kernel code: `memory/mmu.rs`](#generic-kernel-code-memorymmurs) - * [BSP: `bsp/raspberrypi/memory/mmu.rs`](#bsp-bspraspberrypimemorymmurs) - * [AArch64: `_arch/aarch64/memory/mmu.rs`](#aarch64-_archaarch64memorymmurs) - * [`link.ld`](#linkld) -- [Address translation examples](#address-translation-examples) - * [Address translation using a 64 KiB page descriptor](#address-translation-using-a-64-kib-page-descriptor) -- [Zero-cost abstraction](#zero-cost-abstraction) -- [Test it](#test-it) -- [Diff to previous](#diff-to-previous) - -## Introduction - -Virtual memory is an immensely complex, but important and powerful topic. In this tutorial, we start -slow and easy by switching on the `MMU`, using static translation tables and `identity-map` -everything at once (except for the `UART`, which we remap for educational purposes; This will be -gone again in the next tutorial). - -## MMU and paging theory - -At this point, we will not re-invent the wheel and go into detailed descriptions of how paging in -modern application-grade processors works. The internet is full of great resources regarding this -topic, and we encourage you to read some of it to get a high-level understanding of the topic. - -To follow the rest of this `AArch64` specific tutorial, I strongly recommend that you stop right -here and first read `Chapter 12` of the [ARM Cortex-A Series Programmer's Guide for ARMv8-A] before -you continue. This will set you up with all the `AArch64`-specific knowledge needed to follow along. - -Back from reading `Chapter 12` already? Good job :+1:! - -[ARM Cortex-A Series Programmer's Guide for ARMv8-A]: http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf - -## Approach - -1. The generic `kernel` part: `src/memory/mmu.rs` provides architecture-agnostic descriptor types - for composing a high-level data structure that describes the kernel's virtual memory layout: - `memory::mmu::KernelVirtualLayout`. -2. The `BSP` part: `src/bsp/raspberrypi/memory/mmu.rs` contains a static instance of - `KernelVirtualLayout` and makes it accessible through the function - `bsp::memory::mmu::virt_mem_layout()`. -3. The `aarch64` part: `src/_arch/aarch64/memory/mmu.rs` contains the actual `MMU` driver. It picks - up the `BSP`'s high-level `KernelVirtualLayout` and maps it using a `64 KiB` granule. - -### Generic Kernel code: `memory/mmu.rs` - -The descriptor types provided in this file are building blocks which help to describe attributes of -different memory regions. For example, `R/W`, `no-execute`, `cached/uncached`, and so on. - -The descriptors are agnostic of the hardware `MMU`'s actual descriptors. Different `BSP`s can use -these types to produce a high-level description of the kernel's virtual memory layout. The actual -`MMU` driver for the real HW will consume these types as an input. - -This way, we achieve a clean abstraction between `BSP` and `_arch` code, which allows exchanging one -without needing to adapt the other. - -### BSP: `bsp/raspberrypi/memory/mmu.rs` - -This file contains an instance of `KernelVirtualLayout`, which stores the descriptors mentioned -previously. The `BSP` is the correct place to do this, because it has knowledge of the target -board's memory map. - -The policy is to only describe regions that are **not** ordinary, normal chacheable DRAM. However, -nothing prevents you from defining those too if you wish to. Here is an example for the device MMIO -region: - -```rust -TranslationDescriptor { - name: "Device MMIO", - virtual_range: mmio_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, -}, -``` - -`KernelVirtualLayout` itself implements the following method: - -```rust -pub fn virt_addr_properties( - &self, - virt_addr: usize, -) -> Result<(usize, AttributeFields), &'static str> -``` - -It will be used by the `_arch/aarch64`'s `MMU` code to request attributes for a virtual address and -the translation, which delivers the physical output address (the `usize` in the return-tuple). The -function scans for a descriptor that contains the queried address, and returns the respective -findings for the first entry that is a hit. If no entry is found, it returns default attributes for -normal chacheable DRAM and the input address, hence telling the `MMU` code that the requested -address should be `identity mapped`. - -Due to this default return, it is technicall not needed to define normal cacheable DRAM regions. - -### AArch64: `_arch/aarch64/memory/mmu.rs` - -This file contains the `AArch64` `MMU` driver. The granule is hardcoded here (`64 KiB` page -descriptors). - -The actual translation tables are stored in a global instance of the `ArchTranslationTable` struct: - -```rust -/// A table descriptor for 64 KiB aperture. -/// -/// The output points to the next table. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct TableDescriptor(InMemoryRegister); - -/// A page descriptor with 64 KiB aperture. -/// -/// The output points to physical memory. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct PageDescriptor(InMemoryRegister); - -/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB -/// aligned, hence the "reverse" order of appearance. -#[repr(C)] -#[repr(align(65536))] -struct FixedSizeTranslationTable { - /// Page descriptors, covering 64 KiB windows per entry. - lvl3: [[PageDescriptor; 8192]; NUM_TABLES], - - /// Table descriptors, covering 512 MiB windows. - lvl2: [TableDescriptor; NUM_TABLES], -} - -/// Usually evaluates to 1 GiB for RPi3 and 4 GiB for RPi 4. -const NUM_LVL2_TABLES: usize = bsp::memory::mmu::addr_space_size() >> FIVETWELVE_MIB_SHIFT; -type ArchTranslationTable = FixedSizeTranslationTable; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -/// The translation tables. -/// -/// # Safety -/// -/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". -static mut KERNEL_TABLES: ArchTranslationTable = ArchTranslationTable::new(); -``` - -They are populated using `bsp::memory::mmu::virt_mem_layout().virt_addr_properties()` and a bunch of -utility functions that convert our own descriptors to the actual `64 bit` integer entries needed by -the `MMU` hardware for the translation table arrays. - -Each page descriptor has an entry (`AttrIndex`) that indexes into the [MAIR_EL1] register, which -holds information about the cacheability of the respective page. We currently define normal -cacheable memory and device memory (which is not cached). - -[MAIR_EL1]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500d/CIHDHJBB.html - -```rust -/// Setup function for the MAIR_EL1 register. -fn set_up_mair() { - // Define the memory types being mapped. - MAIR_EL1.write( - // Attribute 1 - Cacheable normal DRAM. - MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + - MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + - - // Attribute 0 - Device. - MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, - ); -} -``` - -Afterwards, the [Translation Table Base Register 0 - EL1] is set up with the base address of the -`lvl2` tables and the [Translation Control Register - EL1] is configured. - -Finally, the `MMU` is turned on through the [System Control Register - EL1]. The last step also -enables caching for data and instructions. - -[Translation Table Base Register 0 - EL1]: https://docs.rs/crate/cortex-a/2.4.0/source/src/regs/ttbr0_el1.rs -[Translation Control Register - EL1]: https://docs.rs/crate/cortex-a/2.4.0/source/src/regs/tcr_el1.rs -[System Control Register - EL1]: https://docs.rs/crate/cortex-a/2.4.0/source/src/regs/sctlr_el1.rs - -### `link.ld` - -We need to align the `ro` section to `64 KiB` so that it doesn't overlap with the next section that -needs read/write attributes. This blows up the binary in size, but is a small price to pay -considering that it reduces the amount of static paging entries significantly, when compared to the -classical `4 KiB` granule. - -## Address translation examples - -For educational purposes, a layout is defined which allows to access the `UART` via two different -virtual addresses: -- Since we identity map the whole `Device MMIO` region, it is accessible by asserting its physical - base address (`0x3F20_1000` or `0xFA20_1000` depending on which RPi you use) after the `MMU` is - turned on. -- Additionally, it is also mapped into the last `64 KiB` entry of the `lvl3` table, making it - accessible through base address `0x1FFF_1000`. - -The following block diagram visualizes the underlying translation for the second mapping. - -### Address translation using a 64 KiB page descriptor - -Page Tables 64KiB - -## Zero-cost abstraction - -The MMU init code is again a good example to see the great potential of Rust's zero-cost -abstractions[[1]][[2]] for embedded programming. - -Let's take a look again at the piece of code for setting up the `MAIR_EL1` register using the -[cortex-a] crate: - -[1]: https://blog.rust-lang.org/2015/05/11/traits.html -[2]: https://ruudvanasseldonk.com/2016/11/30/zero-cost-abstractions -[cortex-a]: https://crates.io/crates/cortex-a - -```rust -/// Setup function for the MAIR_EL1 register. -fn set_up_mair() { - // Define the memory types being mapped. - MAIR_EL1.write( - // Attribute 1 - Cacheable normal DRAM. - MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + - MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + - - // Attribute 0 - Device. - MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, - ); -} -``` - -This piece of code is super expressive, and it makes use of `traits`, different `types` and -`constants` to provide type-safe register manipulation. - -In the end, this code sets the first four bytes of the register to certain values according to the -data sheet. Looking at the generated code, we can see that despite all the type-safety and -abstractions, it boils down to two assembly instructions: - -```text -0000000000081660 <::init>: - ... - 816bc: 529fe088 mov w8, #0xff04 - ... - 816c4: d518a208 msr mair_el1, x8 -``` - -## Test it - -```console -$ make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 3 - -[ML] Requesting binary -[MP] ⏩ Pushing 64 KiB ========================================🦀 100% 32 KiB/s Time: 00:00:02 -[ML] Loaded! Executing the payload now - -[ 3.085343] Booting on: Raspberry Pi 3 -[ 3.086427] MMU online. Special regions: -[ 3.088339] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data -[ 3.092422] 0x1fff0000 - 0x1fffffff | 64 KiB | Dev RW PXN | Remapped Device MMIO -[ 3.096375] 0x3f000000 - 0x4000ffff | 16 MiB | Dev RW PXN | Device MMIO -[ 3.099937] Current privilege level: EL1 -[ 3.101848] Exception handling state: -[ 3.103629] Debug: Masked -[ 3.105192] SError: Masked -[ 3.106756] IRQ: Masked -[ 3.108320] FIQ: Masked -[ 3.109884] Architectural timer resolution: 52 ns -[ 3.112186] Drivers loaded: -[ 3.113532] 1. BCM GPIO -[ 3.114966] 2. BCM PL011 UART -[ 3.116660] Timer test, spinning for 1 second -[ !!! ] Writing through the remapped UART at 0x1FFF_1000 -[ 4.120828] Echoing input now -``` - -## Diff to previous -```diff - -diff -uNr 10_privilege_level/src/_arch/aarch64/memory/mmu.rs 11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs ---- 10_privilege_level/src/_arch/aarch64/memory/mmu.rs -+++ 11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs -@@ -0,0 +1,333 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! Memory Management Unit Driver. -+//! -+//! Static translation tables, compiled on boot; Everything 64 KiB granule. -+ -+use super::{AccessPermissions, AttributeFields, MemAttributes}; -+use crate::{bsp, memory}; -+use core::convert; -+use cortex_a::{barrier, regs::*}; -+use register::{register_bitfields, InMemoryRegister}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. -+register_bitfields! {u64, -+ STAGE1_TABLE_DESCRIPTOR [ -+ /// Physical address of the next descriptor. -+ NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] -+ -+ TYPE OFFSET(1) NUMBITS(1) [ -+ Block = 0, -+ Table = 1 -+ ], -+ -+ VALID OFFSET(0) NUMBITS(1) [ -+ False = 0, -+ True = 1 -+ ] -+ ] -+} -+ -+// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. -+register_bitfields! {u64, -+ STAGE1_PAGE_DESCRIPTOR [ -+ /// Privileged execute-never. -+ PXN OFFSET(53) NUMBITS(1) [ -+ False = 0, -+ True = 1 -+ ], -+ -+ /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). -+ OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] -+ -+ /// Access flag. -+ AF OFFSET(10) NUMBITS(1) [ -+ False = 0, -+ True = 1 -+ ], -+ -+ /// Shareability field. -+ SH OFFSET(8) NUMBITS(2) [ -+ OuterShareable = 0b10, -+ InnerShareable = 0b11 -+ ], -+ -+ /// Access Permissions. -+ AP OFFSET(6) NUMBITS(2) [ -+ RW_EL1 = 0b00, -+ RW_EL1_EL0 = 0b01, -+ RO_EL1 = 0b10, -+ RO_EL1_EL0 = 0b11 -+ ], -+ -+ /// Memory attributes index into the MAIR_EL1 register. -+ AttrIndx OFFSET(2) NUMBITS(3) [], -+ -+ TYPE OFFSET(1) NUMBITS(1) [ -+ Block = 0, -+ Table = 1 -+ ], -+ -+ VALID OFFSET(0) NUMBITS(1) [ -+ False = 0, -+ True = 1 -+ ] -+ ] -+} -+ -+const SIXTYFOUR_KIB_SHIFT: usize = 16; // log2(64 * 1024) -+const FIVETWELVE_MIB_SHIFT: usize = 29; // log2(512 * 1024 * 1024) -+ -+/// A table descriptor for 64 KiB aperture. -+/// -+/// The output points to the next table. -+#[derive(Copy, Clone)] -+#[repr(transparent)] -+struct TableDescriptor(u64); -+ -+/// A page descriptor with 64 KiB aperture. -+/// -+/// The output points to physical memory. -+#[derive(Copy, Clone)] -+#[repr(transparent)] -+struct PageDescriptor(u64); -+ -+/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB -+/// aligned, hence the "reverse" order of appearance. -+#[repr(C)] -+#[repr(align(65536))] -+struct FixedSizeTranslationTable { -+ /// Page descriptors, covering 64 KiB windows per entry. -+ lvl3: [[PageDescriptor; 8192]; NUM_TABLES], -+ -+ /// Table descriptors, covering 512 MiB windows. -+ lvl2: [TableDescriptor; NUM_TABLES], -+} -+ -+/// Usually evaluates to 1 GiB for RPi3 and 4 GiB for RPi 4. -+const NUM_LVL2_TABLES: usize = bsp::memory::mmu::addr_space_size() >> FIVETWELVE_MIB_SHIFT; -+type ArchTranslationTable = FixedSizeTranslationTable; -+ -+trait BaseAddr { -+ fn base_addr_u64(&self) -> u64; -+ fn base_addr_usize(&self) -> usize; -+} -+ -+/// Constants for indexing the MAIR_EL1. -+#[allow(dead_code)] -+mod mair { -+ pub const DEVICE: u64 = 0; -+ pub const NORMAL: u64 = 1; -+} -+ -+/// Memory Management Unit type. -+struct MemoryManagementUnit; -+ -+//-------------------------------------------------------------------------------------------------- -+// Global instances -+//-------------------------------------------------------------------------------------------------- -+ -+/// The translation tables. -+/// -+/// # Safety -+/// -+/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". -+static mut KERNEL_TABLES: ArchTranslationTable = ArchTranslationTable::new(); -+ -+static MMU: MemoryManagementUnit = MemoryManagementUnit; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl BaseAddr for [T; N] { -+ fn base_addr_u64(&self) -> u64 { -+ self as *const T as u64 -+ } -+ -+ fn base_addr_usize(&self) -> usize { -+ self as *const _ as usize -+ } -+} -+ -+impl convert::From for TableDescriptor { -+ fn from(next_lvl_table_addr: usize) -> Self { -+ let val = InMemoryRegister::::new(0); -+ -+ let shifted = next_lvl_table_addr >> SIXTYFOUR_KIB_SHIFT; -+ val.write( -+ STAGE1_TABLE_DESCRIPTOR::VALID::True -+ + STAGE1_TABLE_DESCRIPTOR::TYPE::Table -+ + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64), -+ ); -+ -+ TableDescriptor(val.get()) -+ } -+} -+ -+/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. -+impl convert::From -+ for register::FieldValue -+{ -+ fn from(attribute_fields: AttributeFields) -> Self { -+ // Memory attributes. -+ let mut desc = match attribute_fields.mem_attributes { -+ MemAttributes::CacheableDRAM => { -+ STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable -+ + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::NORMAL) -+ } -+ MemAttributes::Device => { -+ STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable -+ + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::DEVICE) -+ } -+ }; -+ -+ // Access Permissions. -+ desc += match attribute_fields.acc_perms { -+ AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, -+ AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, -+ }; -+ -+ // Execute Never. -+ desc += if attribute_fields.execute_never { -+ STAGE1_PAGE_DESCRIPTOR::PXN::True -+ } else { -+ STAGE1_PAGE_DESCRIPTOR::PXN::False -+ }; -+ -+ desc -+ } -+} -+ -+impl PageDescriptor { -+ /// Create an instance. -+ fn new(output_addr: usize, attribute_fields: AttributeFields) -> Self { -+ let val = InMemoryRegister::::new(0); -+ -+ let shifted = output_addr as u64 >> SIXTYFOUR_KIB_SHIFT; -+ val.write( -+ STAGE1_PAGE_DESCRIPTOR::VALID::True -+ + STAGE1_PAGE_DESCRIPTOR::AF::True -+ + attribute_fields.into() -+ + STAGE1_PAGE_DESCRIPTOR::TYPE::Table -+ + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted), -+ ); -+ -+ Self(val.get()) -+ } -+} -+ -+impl FixedSizeTranslationTable<{ NUM_TABLES }> { -+ /// Create an instance. -+ pub const fn new() -> Self { -+ assert!(NUM_TABLES > 0); -+ -+ Self { -+ lvl3: [[PageDescriptor(0); 8192]; NUM_TABLES], -+ lvl2: [TableDescriptor(0); NUM_TABLES], -+ } -+ } -+} -+ -+/// Setup function for the MAIR_EL1 register. -+fn set_up_mair() { -+ // Define the memory types being mapped. -+ MAIR_EL1.write( -+ // Attribute 1 - Cacheable normal DRAM. -+ MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + -+ MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + -+ -+ // Attribute 0 - Device. -+ MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, -+ ); -+} -+ -+/// Iterates over all static translation table entries and fills them at once. -+/// -+/// # Safety -+/// -+/// - Modifies a `static mut`. Ensure it only happens from here. -+unsafe fn populate_tt_entries() -> Result<(), &'static str> { -+ for (l2_nr, l2_entry) in KERNEL_TABLES.lvl2.iter_mut().enumerate() { -+ *l2_entry = KERNEL_TABLES.lvl3[l2_nr].base_addr_usize().into(); -+ -+ for (l3_nr, l3_entry) in KERNEL_TABLES.lvl3[l2_nr].iter_mut().enumerate() { -+ let virt_addr = (l2_nr << FIVETWELVE_MIB_SHIFT) + (l3_nr << SIXTYFOUR_KIB_SHIFT); -+ -+ let (output_addr, attribute_fields) = -+ bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; -+ -+ *l3_entry = PageDescriptor::new(output_addr, attribute_fields); -+ } -+ } -+ -+ Ok(()) -+} -+ -+/// Configure various settings of stage 1 of the EL1 translation regime. -+fn configure_translation_control() { -+ let ips = ID_AA64MMFR0_EL1.read(ID_AA64MMFR0_EL1::PARange); -+ -+ TCR_EL1.write( -+ TCR_EL1::TBI0::Ignored -+ + TCR_EL1::IPS.val(ips) -+ + TCR_EL1::TG0::KiB_64 -+ + TCR_EL1::SH0::Inner -+ + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable -+ + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable -+ + TCR_EL1::EPD0::EnableTTBR0Walks -+ + TCR_EL1::T0SZ.val(32), // TTBR0 spans 4 GiB total. -+ ); -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return a reference to the MMU instance. -+pub fn mmu() -> &'static impl memory::mmu::interface::MMU { -+ &MMU -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+ -+impl memory::mmu::interface::MMU for MemoryManagementUnit { -+ unsafe fn init(&self) -> Result<(), &'static str> { -+ // Fail early if translation granule is not supported. Both RPis support it, though. -+ if !ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported) { -+ return Err("Translation granule not supported in HW"); -+ } -+ -+ // Prepare the memory attribute indirection register. -+ set_up_mair(); -+ -+ // Populate translation tables. -+ populate_tt_entries()?; -+ -+ // Set the "Translation Table Base Register". -+ TTBR0_EL1.set_baddr(KERNEL_TABLES.lvl2.base_addr_u64()); -+ -+ configure_translation_control(); -+ -+ // Switch the MMU on. -+ // -+ // First, force all previous changes to be seen before the MMU is enabled. -+ barrier::isb(barrier::SY); -+ -+ // Enable the MMU and turn on data and instruction caching. -+ SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); -+ -+ // Force MMU init to complete before next instruction. -+ barrier::isb(barrier::SY); -+ -+ Ok(()) -+ } -+} - -diff -uNr 10_privilege_level/src/bsp/raspberrypi/link.ld 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld ---- 10_privilege_level/src/bsp/raspberrypi/link.ld -+++ 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld -@@ -8,6 +8,7 @@ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - -+ __ro_start = .; - .text : - { - *(.text._start) *(.text*) -@@ -17,6 +18,8 @@ - { - *(.rodata*) - } -+ . = ALIGN(65536); /* Fill up to 64 KiB */ -+ __ro_end = .; - - .data : - { - -diff -uNr 10_privilege_level/src/bsp/raspberrypi/memory/mmu.rs 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs ---- 10_privilege_level/src/bsp/raspberrypi/memory/mmu.rs -+++ 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs -@@ -0,0 +1,88 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+//! BSP Memory Management Unit. -+ -+use super::map as memory_map; -+use crate::memory::mmu::*; -+use core::ops::RangeInclusive; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+const NUM_MEM_RANGES: usize = 3; -+ -+/// The virtual memory layout. -+/// -+/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. -+/// It is agnostic of the paging granularity that the architecture's MMU will use. -+pub static LAYOUT: KernelVirtualLayout<{ NUM_MEM_RANGES }> = KernelVirtualLayout::new( -+ memory_map::END_INCLUSIVE, -+ [ -+ TranslationDescriptor { -+ name: "Kernel code and RO data", -+ virtual_range: ro_range_inclusive, -+ physical_range_translation: Translation::Identity, -+ attribute_fields: AttributeFields { -+ mem_attributes: MemAttributes::CacheableDRAM, -+ acc_perms: AccessPermissions::ReadOnly, -+ execute_never: false, -+ }, -+ }, -+ TranslationDescriptor { -+ name: "Remapped Device MMIO", -+ virtual_range: remapped_mmio_range_inclusive, -+ physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), -+ attribute_fields: AttributeFields { -+ mem_attributes: MemAttributes::Device, -+ acc_perms: AccessPermissions::ReadWrite, -+ execute_never: true, -+ }, -+ }, -+ TranslationDescriptor { -+ name: "Device MMIO", -+ virtual_range: mmio_range_inclusive, -+ physical_range_translation: Translation::Identity, -+ attribute_fields: AttributeFields { -+ mem_attributes: MemAttributes::Device, -+ acc_perms: AccessPermissions::ReadWrite, -+ execute_never: true, -+ }, -+ }, -+ ], -+); -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+fn ro_range_inclusive() -> RangeInclusive { -+ // Notice the subtraction to turn the exclusive end into an inclusive end. -+ #[allow(clippy::range_minus_one)] -+ RangeInclusive::new(super::ro_start(), super::ro_end() - 1) -+} -+ -+fn remapped_mmio_range_inclusive() -> RangeInclusive { -+ // The last 64 KiB slot in the first 512 MiB -+ RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) -+} -+ -+fn mmio_range_inclusive() -> RangeInclusive { -+ RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return the address space size in bytes. -+pub const fn addr_space_size() -> usize { -+ memory_map::END_INCLUSIVE + 1 -+} -+ -+/// Return a reference to the virtual memory layout. -+pub fn virt_mem_layout() -> &'static KernelVirtualLayout<{ NUM_MEM_RANGES }> { -+ &LAYOUT -+} - -diff -uNr 10_privilege_level/src/bsp/raspberrypi/memory.rs 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs ---- 10_privilege_level/src/bsp/raspberrypi/memory.rs -+++ 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs -@@ -4,6 +4,8 @@ - - //! BSP Memory Management. - -+pub mod mmu; -+ - use core::{cell::UnsafeCell, ops::RangeInclusive}; - - //-------------------------------------------------------------------------------------------------- -@@ -14,6 +16,8 @@ - extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -+ static __ro_start: UnsafeCell<()>; -+ static __ro_end: UnsafeCell<()>; - } - - //-------------------------------------------------------------------------------------------------- -@@ -23,6 +27,8 @@ - /// The board's memory map. - #[rustfmt::skip] - pub(super) mod map { -+ pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; -+ - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; -@@ -36,6 +42,7 @@ - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; -+ pub const END_INCLUSIVE: usize = 0x4000_FFFF; - } - - /// Physical devices. -@@ -46,10 +53,35 @@ - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; -+ pub const END_INCLUSIVE: usize = 0xFF84_FFFF; - } - } - - //-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Start address of the Read-Only (RO) range. -+/// -+/// # Safety -+/// -+/// - Value is provided by the linker script and must be trusted as-is. -+#[inline(always)] -+fn ro_start() -> usize { -+ unsafe { __ro_start.get() as usize } -+} -+ -+/// Size of the Read-Only (RO) range of the kernel binary. -+/// -+/// # Safety -+/// -+/// - Value is provided by the linker script and must be trusted as-is. -+#[inline(always)] -+fn ro_end() -> usize { -+ unsafe { __ro_end.get() as usize } -+} -+ -+//-------------------------------------------------------------------------------------------------- - // Public Code - //-------------------------------------------------------------------------------------------------- - - -diff -uNr 10_privilege_level/src/bsp.rs 11_virtual_mem_part1_identity_mapping/src/bsp.rs ---- 10_privilege_level/src/bsp.rs -+++ 11_virtual_mem_part1_identity_mapping/src/bsp.rs -@@ -4,7 +4,7 @@ - - //! Conditional re-exporting of Board Support Packages. - --mod device_driver; -+pub mod device_driver; - - #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] - mod raspberrypi; - -diff -uNr 10_privilege_level/src/main.rs 11_virtual_mem_part1_identity_mapping/src/main.rs ---- 10_privilege_level/src/main.rs -+++ 11_virtual_mem_part1_identity_mapping/src/main.rs -@@ -11,10 +11,12 @@ - //! - //! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. - //! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -+//! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. - //! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. - //! - //! [console interface]: ../libkernel/console/interface/index.html - //! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -+//! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html - //! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html - //! - //! # Code organization and architecture -@@ -102,7 +104,10 @@ - //! - `crate::memory::*` - //! - `crate::bsp::memory::*` - -+#![allow(incomplete_features)] - #![feature(const_fn_fn_ptr_basics)] -+#![feature(const_generics)] -+#![feature(const_panic)] - #![feature(format_args_nl)] - #![feature(naked_functions)] - #![feature(panic_info_message)] -@@ -130,9 +135,18 @@ - /// # Safety - /// - /// - Only a single core must be active and running this function. --/// - The init calls in this function must appear in the correct order. -+/// - The init calls in this function must appear in the correct order: -+/// - Virtual memory must be activated before the device drivers. -+/// - Without it, any atomic operations, e.g. the yet-to-be-introduced spinlocks in the device -+/// drivers (which currently employ NullLocks instead of spinlocks), will fail to work on -+/// the RPi SoCs. - unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; -+ use memory::mmu::interface::MMU; -+ -+ if let Err(string) = memory::mmu::mmu().init() { -+ panic!("MMU: {}", string); -+ } - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { -@@ -155,6 +169,9 @@ - - info!("Booting on: {}", bsp::board_name()); - -+ info!("MMU online. Special regions:"); -+ bsp::memory::mmu::virt_mem_layout().print_layout(); -+ - let (_, privilege_level) = exception::current_privilege_level(); - info!("Current privilege level: {}", privilege_level); - -@@ -178,6 +195,13 @@ - info!("Timer test, spinning for 1 second"); - time::time_manager().spin_for(Duration::from_secs(1)); - -+ let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; -+ writeln!( -+ remapped_uart, -+ "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" -+ ) -+ .unwrap(); -+ - info!("Echoing input now"); - loop { - let c = bsp::console::console().read_char(); - -diff -uNr 10_privilege_level/src/memory/mmu.rs 11_virtual_mem_part1_identity_mapping/src/memory/mmu.rs ---- 10_privilege_level/src/memory/mmu.rs -+++ 11_virtual_mem_part1_identity_mapping/src/memory/mmu.rs -@@ -0,0 +1,199 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Memory Management Unit. -+//! -+//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file -+//! provides types for composing an architecture-agnostic description of the kernel 's virtual -+//! memory layout. -+//! -+//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` -+//! function. -+//! -+//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and -+//! install respective translation tables. -+ -+#[cfg(target_arch = "aarch64")] -+#[path = "../_arch/aarch64/memory/mmu.rs"] -+mod arch_mmu; -+pub use arch_mmu::*; -+ -+use core::{fmt, ops::RangeInclusive}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Memory Management interfaces. -+pub mod interface { -+ -+ /// MMU functions. -+ pub trait MMU { -+ /// Called by the kernel during early init. Supposed to take the translation tables from the -+ /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. -+ /// -+ /// # Safety -+ /// -+ /// - Changes the HW's global state. -+ unsafe fn init(&self) -> Result<(), &'static str>; -+ } -+} -+ -+/// Architecture agnostic translation types. -+#[allow(missing_docs)] -+#[derive(Copy, Clone)] -+pub enum Translation { -+ Identity, -+ Offset(usize), -+} -+ -+/// Architecture agnostic memory attributes. -+#[allow(missing_docs)] -+#[derive(Copy, Clone)] -+pub enum MemAttributes { -+ CacheableDRAM, -+ Device, -+} -+ -+/// Architecture agnostic access permissions. -+#[allow(missing_docs)] -+#[derive(Copy, Clone)] -+pub enum AccessPermissions { -+ ReadOnly, -+ ReadWrite, -+} -+ -+/// Collection of memory attributes. -+#[allow(missing_docs)] -+#[derive(Copy, Clone)] -+pub struct AttributeFields { -+ pub mem_attributes: MemAttributes, -+ pub acc_perms: AccessPermissions, -+ pub execute_never: bool, -+} -+ -+/// Architecture agnostic descriptor for a memory range. -+#[allow(missing_docs)] -+pub struct TranslationDescriptor { -+ pub name: &'static str, -+ pub virtual_range: fn() -> RangeInclusive, -+ pub physical_range_translation: Translation, -+ pub attribute_fields: AttributeFields, -+} -+ -+/// Type for expressing the kernel's virtual memory layout. -+pub struct KernelVirtualLayout { -+ /// The last (inclusive) address of the address space. -+ max_virt_addr_inclusive: usize, -+ -+ /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. -+ inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl Default for AttributeFields { -+ fn default() -> AttributeFields { -+ AttributeFields { -+ mem_attributes: MemAttributes::CacheableDRAM, -+ acc_perms: AccessPermissions::ReadWrite, -+ execute_never: true, -+ } -+ } -+} -+ -+/// Human-readable output of a TranslationDescriptor. -+impl fmt::Display for TranslationDescriptor { -+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -+ // Call the function to which self.range points, and dereference the result, which causes -+ // Rust to copy the value. -+ let start = *(self.virtual_range)().start(); -+ let end = *(self.virtual_range)().end(); -+ let size = end - start + 1; -+ -+ // log2(1024). -+ const KIB_RSHIFT: u32 = 10; -+ -+ // log2(1024 * 1024). -+ const MIB_RSHIFT: u32 = 20; -+ -+ let (size, unit) = if (size >> MIB_RSHIFT) > 0 { -+ (size >> MIB_RSHIFT, "MiB") -+ } else if (size >> KIB_RSHIFT) > 0 { -+ (size >> KIB_RSHIFT, "KiB") -+ } else { -+ (size, "Byte") -+ }; -+ -+ let attr = match self.attribute_fields.mem_attributes { -+ MemAttributes::CacheableDRAM => "C", -+ MemAttributes::Device => "Dev", -+ }; -+ -+ let acc_p = match self.attribute_fields.acc_perms { -+ AccessPermissions::ReadOnly => "RO", -+ AccessPermissions::ReadWrite => "RW", -+ }; -+ -+ let xn = if self.attribute_fields.execute_never { -+ "PXN" -+ } else { -+ "PX" -+ }; -+ -+ write!( -+ f, -+ " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", -+ start, end, size, unit, attr, acc_p, xn, self.name -+ ) -+ } -+} -+ -+impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { -+ /// Create a new instance. -+ pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { -+ Self { -+ max_virt_addr_inclusive: max, -+ inner: layout, -+ } -+ } -+ -+ /// For a virtual address, find and return the physical output address and corresponding -+ /// attributes. -+ /// -+ /// If the address is not found in `inner`, return an identity mapped default with normal -+ /// cacheable DRAM attributes. -+ pub fn virt_addr_properties( -+ &self, -+ virt_addr: usize, -+ ) -> Result<(usize, AttributeFields), &'static str> { -+ if virt_addr > self.max_virt_addr_inclusive { -+ return Err("Address out of range"); -+ } -+ -+ for i in self.inner.iter() { -+ if (i.virtual_range)().contains(&virt_addr) { -+ let output_addr = match i.physical_range_translation { -+ Translation::Identity => virt_addr, -+ Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), -+ }; -+ -+ return Ok((output_addr, i.attribute_fields)); -+ } -+ } -+ -+ Ok((virt_addr, AttributeFields::default())) -+ } -+ -+ /// Print the memory layout. -+ pub fn print_layout(&self) { -+ use crate::info; -+ -+ for i in self.inner.iter() { -+ info!("{}", i); -+ } -+ } -+} - -diff -uNr 10_privilege_level/src/memory.rs 11_virtual_mem_part1_identity_mapping/src/memory.rs ---- 10_privilege_level/src/memory.rs -+++ 11_virtual_mem_part1_identity_mapping/src/memory.rs -@@ -4,6 +4,8 @@ - - //! Memory Management. - -+pub mod mmu; -+ - use core::ops::RangeInclusive; - - //-------------------------------------------------------------------------------------------------- - -``` diff --git a/11_virtual_mem_part1_identity_mapping/build.rs b/11_virtual_mem_part1_identity_mapping/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/11_virtual_mem_part1_identity_mapping/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs b/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 3e5e57530..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - // Expect the boot core to start in EL2. - if (bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id()) - && (CurrentEL.get() == CurrentEL::EL::EL2.value) - { - el2_to_el1_transition() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -/// Transition from EL2 to EL1. -/// -/// # Safety -/// -/// - The HW state of EL1 must be prepared in a sound way. -/// - Exception return from EL2 must must continue execution in EL1 with -/// `runtime_init::runtime_init()`. -#[inline(always)] -unsafe fn el2_to_el1_transition() -> ! { - use crate::runtime_init; - - // Enable timer counter registers for EL1. - CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); - - // No offset for reading the counters. - CNTVOFF_EL2.set(0); - - // Set EL1 execution state to AArch64. - HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); - - // Set up a simulated exception return. - // - // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a - // stack pointer. - SPSR_EL2.write( - SPSR_EL2::D::Masked - + SPSR_EL2::A::Masked - + SPSR_EL2::I::Masked - + SPSR_EL2::F::Masked - + SPSR_EL2::M::EL1h, - ); - - // Second, let the link register point to runtime_init(). - ELR_EL2.set(runtime_init::runtime_init as *const () as u64); - - // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. - SP_EL1.set(bsp::memory::boot_core_stack_end() as u64); - - // Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. - asm::eret() -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/smp.rs b/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs b/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs deleted file mode 100644 index ebfef8c82..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural synchronous and asynchronous exception handling. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use crate::exception::PrivilegeLevel; - -/// The processing element's current privilege level. -pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { - let el = CurrentEL.read_as_enum(CurrentEL::EL); - match el { - Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), - Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), - Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), - _ => (PrivilegeLevel::Unknown, "Unknown"), - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception/asynchronous.rs b/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception/asynchronous.rs deleted file mode 100644 index f660544c1..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception/asynchronous.rs +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural asynchronous exception handling. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -trait DaifField { - fn daif_field() -> register::Field; -} - -struct Debug; -struct SError; -struct IRQ; -struct FIQ; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl DaifField for Debug { - fn daif_field() -> register::Field { - DAIF::D - } -} - -impl DaifField for SError { - fn daif_field() -> register::Field { - DAIF::A - } -} - -impl DaifField for IRQ { - fn daif_field() -> register::Field { - DAIF::I - } -} - -impl DaifField for FIQ { - fn daif_field() -> register::Field { - DAIF::F - } -} - -fn is_masked() -> bool -where - T: DaifField, -{ - DAIF.is_set(T::daif_field()) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Print the AArch64 exceptions status. -#[rustfmt::skip] -pub fn print_state() { - use crate::info; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - info!(" Debug: {}", to_mask_str(is_masked::())); - info!(" SError: {}", to_mask_str(is_masked::())); - info!(" IRQ: {}", to_mask_str(is_masked::())); - info!(" FIQ: {}", to_mask_str(is_masked::())); -} diff --git a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs b/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs deleted file mode 100644 index ff653a091..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs +++ /dev/null @@ -1,333 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management Unit Driver. -//! -//! Static translation tables, compiled on boot; Everything 64 KiB granule. - -use super::{AccessPermissions, AttributeFields, MemAttributes}; -use crate::{bsp, memory}; -use core::convert; -use cortex_a::{barrier, regs::*}; -use register::{register_bitfields, InMemoryRegister}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. -register_bitfields! {u64, - STAGE1_TABLE_DESCRIPTOR [ - /// Physical address of the next descriptor. - NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. -register_bitfields! {u64, - STAGE1_PAGE_DESCRIPTOR [ - /// Privileged execute-never. - PXN OFFSET(53) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). - OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - /// Access flag. - AF OFFSET(10) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Shareability field. - SH OFFSET(8) NUMBITS(2) [ - OuterShareable = 0b10, - InnerShareable = 0b11 - ], - - /// Access Permissions. - AP OFFSET(6) NUMBITS(2) [ - RW_EL1 = 0b00, - RW_EL1_EL0 = 0b01, - RO_EL1 = 0b10, - RO_EL1_EL0 = 0b11 - ], - - /// Memory attributes index into the MAIR_EL1 register. - AttrIndx OFFSET(2) NUMBITS(3) [], - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -const SIXTYFOUR_KIB_SHIFT: usize = 16; // log2(64 * 1024) -const FIVETWELVE_MIB_SHIFT: usize = 29; // log2(512 * 1024 * 1024) - -/// A table descriptor for 64 KiB aperture. -/// -/// The output points to the next table. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct TableDescriptor(u64); - -/// A page descriptor with 64 KiB aperture. -/// -/// The output points to physical memory. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct PageDescriptor(u64); - -/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB -/// aligned, hence the "reverse" order of appearance. -#[repr(C)] -#[repr(align(65536))] -struct FixedSizeTranslationTable { - /// Page descriptors, covering 64 KiB windows per entry. - lvl3: [[PageDescriptor; 8192]; NUM_TABLES], - - /// Table descriptors, covering 512 MiB windows. - lvl2: [TableDescriptor; NUM_TABLES], -} - -/// Usually evaluates to 1 GiB for RPi3 and 4 GiB for RPi 4. -const NUM_LVL2_TABLES: usize = bsp::memory::mmu::addr_space_size() >> FIVETWELVE_MIB_SHIFT; -type ArchTranslationTable = FixedSizeTranslationTable; - -trait BaseAddr { - fn base_addr_u64(&self) -> u64; - fn base_addr_usize(&self) -> usize; -} - -/// Constants for indexing the MAIR_EL1. -#[allow(dead_code)] -mod mair { - pub const DEVICE: u64 = 0; - pub const NORMAL: u64 = 1; -} - -/// Memory Management Unit type. -struct MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -/// The translation tables. -/// -/// # Safety -/// -/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". -static mut KERNEL_TABLES: ArchTranslationTable = ArchTranslationTable::new(); - -static MMU: MemoryManagementUnit = MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl BaseAddr for [T; N] { - fn base_addr_u64(&self) -> u64 { - self as *const T as u64 - } - - fn base_addr_usize(&self) -> usize { - self as *const _ as usize - } -} - -impl convert::From for TableDescriptor { - fn from(next_lvl_table_addr: usize) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = next_lvl_table_addr >> SIXTYFOUR_KIB_SHIFT; - val.write( - STAGE1_TABLE_DESCRIPTOR::VALID::True - + STAGE1_TABLE_DESCRIPTOR::TYPE::Table - + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64), - ); - - TableDescriptor(val.get()) - } -} - -/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. -impl convert::From - for register::FieldValue -{ - fn from(attribute_fields: AttributeFields) -> Self { - // Memory attributes. - let mut desc = match attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => { - STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::NORMAL) - } - MemAttributes::Device => { - STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::DEVICE) - } - }; - - // Access Permissions. - desc += match attribute_fields.acc_perms { - AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, - AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, - }; - - // Execute Never. - desc += if attribute_fields.execute_never { - STAGE1_PAGE_DESCRIPTOR::PXN::True - } else { - STAGE1_PAGE_DESCRIPTOR::PXN::False - }; - - desc - } -} - -impl PageDescriptor { - /// Create an instance. - fn new(output_addr: usize, attribute_fields: AttributeFields) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = output_addr as u64 >> SIXTYFOUR_KIB_SHIFT; - val.write( - STAGE1_PAGE_DESCRIPTOR::VALID::True - + STAGE1_PAGE_DESCRIPTOR::AF::True - + attribute_fields.into() - + STAGE1_PAGE_DESCRIPTOR::TYPE::Table - + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted), - ); - - Self(val.get()) - } -} - -impl FixedSizeTranslationTable<{ NUM_TABLES }> { - /// Create an instance. - pub const fn new() -> Self { - assert!(NUM_TABLES > 0); - - Self { - lvl3: [[PageDescriptor(0); 8192]; NUM_TABLES], - lvl2: [TableDescriptor(0); NUM_TABLES], - } - } -} - -/// Setup function for the MAIR_EL1 register. -fn set_up_mair() { - // Define the memory types being mapped. - MAIR_EL1.write( - // Attribute 1 - Cacheable normal DRAM. - MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + - MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + - - // Attribute 0 - Device. - MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, - ); -} - -/// Iterates over all static translation table entries and fills them at once. -/// -/// # Safety -/// -/// - Modifies a `static mut`. Ensure it only happens from here. -unsafe fn populate_tt_entries() -> Result<(), &'static str> { - for (l2_nr, l2_entry) in KERNEL_TABLES.lvl2.iter_mut().enumerate() { - *l2_entry = KERNEL_TABLES.lvl3[l2_nr].base_addr_usize().into(); - - for (l3_nr, l3_entry) in KERNEL_TABLES.lvl3[l2_nr].iter_mut().enumerate() { - let virt_addr = (l2_nr << FIVETWELVE_MIB_SHIFT) + (l3_nr << SIXTYFOUR_KIB_SHIFT); - - let (output_addr, attribute_fields) = - bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; - - *l3_entry = PageDescriptor::new(output_addr, attribute_fields); - } - } - - Ok(()) -} - -/// Configure various settings of stage 1 of the EL1 translation regime. -fn configure_translation_control() { - let ips = ID_AA64MMFR0_EL1.read(ID_AA64MMFR0_EL1::PARange); - - TCR_EL1.write( - TCR_EL1::TBI0::Ignored - + TCR_EL1::IPS.val(ips) - + TCR_EL1::TG0::KiB_64 - + TCR_EL1::SH0::Inner - + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::EPD0::EnableTTBR0Walks - + TCR_EL1::T0SZ.val(32), // TTBR0 spans 4 GiB total. - ); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the MMU instance. -pub fn mmu() -> &'static impl memory::mmu::interface::MMU { - &MMU -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl memory::mmu::interface::MMU for MemoryManagementUnit { - unsafe fn init(&self) -> Result<(), &'static str> { - // Fail early if translation granule is not supported. Both RPis support it, though. - if !ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported) { - return Err("Translation granule not supported in HW"); - } - - // Prepare the memory attribute indirection register. - set_up_mair(); - - // Populate translation tables. - populate_tt_entries()?; - - // Set the "Translation Table Base Register". - TTBR0_EL1.set_baddr(KERNEL_TABLES.lvl2.base_addr_u64()); - - configure_translation_control(); - - // Switch the MMU on. - // - // First, force all previous changes to be seen before the MMU is enabled. - barrier::isb(barrier::SY); - - // Enable the MMU and turn on data and instruction caching. - SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); - - // Force MMU init to complete before next instruction. - barrier::isb(barrier::SY); - - Ok(()) - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs b/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs deleted file mode 100644 index af98ddd01..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) - } - - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; - - Duration::from_nanos(current_count / frq) - } - - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } - - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get() as u64; - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; - } - - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); - - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); - - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} - - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp.rs b/11_virtual_mem_part1_identity_mapping/src/bsp.rs deleted file mode 100644 index 5add2e382..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -pub mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs deleted file mode 100644 index ce7396f22..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 59071d5d8..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index 15bd3b78b..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; - use core::time::Duration; - - // The Linux 2837 GPIO driver waits 1 µs between the steps. - const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index e39bc7cdb..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,323 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => _reserved3), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Read one character. - let mut ret = inner.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - inner.chars_read += 1; - - ret - }) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/common.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs deleted file mode 100644 index 10888d37f..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/console.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/console.rs deleted file mode 100644 index d1b60dd82..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index fe24dd71b..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld b/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 5b5adbaa6..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,42 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - __ro_start = .; - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - . = ALIGN(65536); /* Fill up to 64 KiB */ - __ro_end = .; - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 810acd8af..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -pub mod mmu; - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; - static __ro_start: UnsafeCell<()>; - static __ro_end: UnsafeCell<()>; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; - - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const END_INCLUSIVE: usize = 0x4000_FFFF; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const END_INCLUSIVE: usize = 0xFF84_FFFF; - } -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Start address of the Read-Only (RO) range. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_start() -> usize { - unsafe { __ro_start.get() as usize } -} - -/// Size of the Read-Only (RO) range of the kernel binary. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_end() -> usize { - unsafe { __ro_end.get() as usize } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs b/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs deleted file mode 100644 index 00990c7ef..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management Unit. - -use super::map as memory_map; -use crate::memory::mmu::*; -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -const NUM_MEM_RANGES: usize = 3; - -/// The virtual memory layout. -/// -/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. -/// It is agnostic of the paging granularity that the architecture's MMU will use. -pub static LAYOUT: KernelVirtualLayout<{ NUM_MEM_RANGES }> = KernelVirtualLayout::new( - memory_map::END_INCLUSIVE, - [ - TranslationDescriptor { - name: "Kernel code and RO data", - virtual_range: ro_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadOnly, - execute_never: false, - }, - }, - TranslationDescriptor { - name: "Remapped Device MMIO", - virtual_range: remapped_mmio_range_inclusive, - physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - }, - TranslationDescriptor { - name: "Device MMIO", - virtual_range: mmio_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - }, - ], -); - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn ro_range_inclusive() -> RangeInclusive { - // Notice the subtraction to turn the exclusive end into an inclusive end. - #[allow(clippy::range_minus_one)] - RangeInclusive::new(super::ro_start(), super::ro_end() - 1) -} - -fn remapped_mmio_range_inclusive() -> RangeInclusive { - // The last 64 KiB slot in the first 512 MiB - RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) -} - -fn mmio_range_inclusive() -> RangeInclusive { - RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the address space size in bytes. -pub const fn addr_space_size() -> usize { - memory_map::END_INCLUSIVE + 1 -} - -/// Return a reference to the virtual memory layout. -pub fn virt_mem_layout() -> &'static KernelVirtualLayout<{ NUM_MEM_RANGES }> { - &LAYOUT -} diff --git a/11_virtual_mem_part1_identity_mapping/src/console.rs b/11_virtual_mem_part1_identity_mapping/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/11_virtual_mem_part1_identity_mapping/src/cpu.rs b/11_virtual_mem_part1_identity_mapping/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/11_virtual_mem_part1_identity_mapping/src/cpu/smp.rs b/11_virtual_mem_part1_identity_mapping/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/11_virtual_mem_part1_identity_mapping/src/driver.rs b/11_virtual_mem_part1_identity_mapping/src/driver.rs deleted file mode 100644 index e2875b876..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/exception.rs b/11_virtual_mem_part1_identity_mapping/src/exception.rs deleted file mode 100644 index d2e621795..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/exception.rs +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronous and asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/exception.rs"] -mod arch_exception; -pub use arch_exception::*; - -pub mod asynchronous; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Kernel privilege levels. -#[allow(missing_docs)] -#[derive(PartialEq)] -pub enum PrivilegeLevel { - User, - Kernel, - Hypervisor, - Unknown, -} diff --git a/11_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs b/11_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs deleted file mode 100644 index 3c75f90a2..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/exception/asynchronous.rs"] -mod arch_exception_async; -pub use arch_exception_async::*; diff --git a/11_virtual_mem_part1_identity_mapping/src/main.rs b/11_virtual_mem_part1_identity_mapping/src/main.rs deleted file mode 100644 index 680e28194..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/main.rs +++ /dev/null @@ -1,210 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![allow(incomplete_features)] -#![feature(const_fn_fn_ptr_basics)] -#![feature(const_generics)] -#![feature(const_panic)] -#![feature(format_args_nl)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod driver; -mod exception; -mod memory; -mod panic_wait; -mod print; -mod runtime_init; -mod synchronization; -mod time; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order: -/// - Virtual memory must be activated before the device drivers. -/// - Without it, any atomic operations, e.g. the yet-to-be-introduced spinlocks in the device -/// drivers (which currently employ NullLocks instead of spinlocks), will fail to work on -/// the RPi SoCs. -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - use memory::mmu::interface::MMU; - - if let Err(string) = memory::mmu::mmu().init() { - panic!("MMU: {}", string); - } - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use console::interface::All; - use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; - - info!("Booting on: {}", bsp::board_name()); - - info!("MMU online. Special regions:"); - bsp::memory::mmu::virt_mem_layout().print_layout(); - - let (_, privilege_level) = exception::current_privilege_level(); - info!("Current privilege level: {}", privilege_level); - - info!("Exception handling state:"); - exception::asynchronous::print_state(); - - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() - ); - - info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } - - info!("Timer test, spinning for 1 second"); - time::time_manager().spin_for(Duration::from_secs(1)); - - let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; - writeln!( - remapped_uart, - "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" - ) - .unwrap(); - - info!("Echoing input now"); - loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/memory.rs b/11_virtual_mem_part1_identity_mapping/src/memory.rs deleted file mode 100644 index 59236a120..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/memory.rs +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -pub mod mmu; - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/memory/mmu.rs b/11_virtual_mem_part1_identity_mapping/src/memory/mmu.rs deleted file mode 100644 index 9675b8ab6..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/memory/mmu.rs +++ /dev/null @@ -1,199 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Memory Management Unit. -//! -//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file -//! provides types for composing an architecture-agnostic description of the kernel 's virtual -//! memory layout. -//! -//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` -//! function. -//! -//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and -//! install respective translation tables. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/memory/mmu.rs"] -mod arch_mmu; -pub use arch_mmu::*; - -use core::{fmt, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Memory Management interfaces. -pub mod interface { - - /// MMU functions. - pub trait MMU { - /// Called by the kernel during early init. Supposed to take the translation tables from the - /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. - /// - /// # Safety - /// - /// - Changes the HW's global state. - unsafe fn init(&self) -> Result<(), &'static str>; - } -} - -/// Architecture agnostic translation types. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum Translation { - Identity, - Offset(usize), -} - -/// Architecture agnostic memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum MemAttributes { - CacheableDRAM, - Device, -} - -/// Architecture agnostic access permissions. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum AccessPermissions { - ReadOnly, - ReadWrite, -} - -/// Collection of memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub struct AttributeFields { - pub mem_attributes: MemAttributes, - pub acc_perms: AccessPermissions, - pub execute_never: bool, -} - -/// Architecture agnostic descriptor for a memory range. -#[allow(missing_docs)] -pub struct TranslationDescriptor { - pub name: &'static str, - pub virtual_range: fn() -> RangeInclusive, - pub physical_range_translation: Translation, - pub attribute_fields: AttributeFields, -} - -/// Type for expressing the kernel's virtual memory layout. -pub struct KernelVirtualLayout { - /// The last (inclusive) address of the address space. - max_virt_addr_inclusive: usize, - - /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. - inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl Default for AttributeFields { - fn default() -> AttributeFields { - AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - } - } -} - -/// Human-readable output of a TranslationDescriptor. -impl fmt::Display for TranslationDescriptor { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Call the function to which self.range points, and dereference the result, which causes - // Rust to copy the value. - let start = *(self.virtual_range)().start(); - let end = *(self.virtual_range)().end(); - let size = end - start + 1; - - // log2(1024). - const KIB_RSHIFT: u32 = 10; - - // log2(1024 * 1024). - const MIB_RSHIFT: u32 = 20; - - let (size, unit) = if (size >> MIB_RSHIFT) > 0 { - (size >> MIB_RSHIFT, "MiB") - } else if (size >> KIB_RSHIFT) > 0 { - (size >> KIB_RSHIFT, "KiB") - } else { - (size, "Byte") - }; - - let attr = match self.attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => "C", - MemAttributes::Device => "Dev", - }; - - let acc_p = match self.attribute_fields.acc_perms { - AccessPermissions::ReadOnly => "RO", - AccessPermissions::ReadWrite => "RW", - }; - - let xn = if self.attribute_fields.execute_never { - "PXN" - } else { - "PX" - }; - - write!( - f, - " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", - start, end, size, unit, attr, acc_p, xn, self.name - ) - } -} - -impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { - /// Create a new instance. - pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { - Self { - max_virt_addr_inclusive: max, - inner: layout, - } - } - - /// For a virtual address, find and return the physical output address and corresponding - /// attributes. - /// - /// If the address is not found in `inner`, return an identity mapped default with normal - /// cacheable DRAM attributes. - pub fn virt_addr_properties( - &self, - virt_addr: usize, - ) -> Result<(usize, AttributeFields), &'static str> { - if virt_addr > self.max_virt_addr_inclusive { - return Err("Address out of range"); - } - - for i in self.inner.iter() { - if (i.virtual_range)().contains(&virt_addr) { - let output_addr = match i.physical_range_translation { - Translation::Identity => virt_addr, - Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), - }; - - return Ok((output_addr, i.attribute_fields)); - } - } - - Ok((virt_addr, AttributeFields::default())) - } - - /// Print the memory layout. - pub fn print_layout(&self) { - use crate::info; - - for i in self.inner.iter() { - info!("{}", i); - } - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/panic_wait.rs b/11_virtual_mem_part1_identity_mapping/src/panic_wait.rs deleted file mode 100644 index 1386e1e23..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/panic_wait.rs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/11_virtual_mem_part1_identity_mapping/src/print.rs b/11_virtual_mem_part1_identity_mapping/src/print.rs deleted file mode 100644 index 8b6f3f988..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/print.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} - -/// Prints an info, with a newline. -#[macro_export] -macro_rules! info { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} - -/// Prints a warning, with a newline. -#[macro_export] -macro_rules! warn { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} diff --git a/11_virtual_mem_part1_identity_mapping/src/runtime_init.rs b/11_virtual_mem_part1_identity_mapping/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/11_virtual_mem_part1_identity_mapping/src/synchronization.rs b/11_virtual_mem_part1_identity_mapping/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/11_virtual_mem_part1_identity_mapping/src/time.rs b/11_virtual_mem_part1_identity_mapping/src/time.rs deleted file mode 100644 index cd3ceec33..000000000 --- a/11_virtual_mem_part1_identity_mapping/src/time.rs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; -pub use arch_time::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); - } -} diff --git a/12_exceptions_part1_groundwork/.vscode/settings.json b/12_exceptions_part1_groundwork/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/12_exceptions_part1_groundwork/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/12_exceptions_part1_groundwork/Cargo.lock b/12_exceptions_part1_groundwork/Cargo.lock deleted file mode 100644 index 7b2456e16..000000000 --- a/12_exceptions_part1_groundwork/Cargo.lock +++ /dev/null @@ -1,33 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "register", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" diff --git a/12_exceptions_part1_groundwork/Cargo.toml b/12_exceptions_part1_groundwork/Cargo.toml deleted file mode 100644 index b8906da1f..000000000 --- a/12_exceptions_part1_groundwork/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] - -# Optional dependencies -register = { version = "1.x.x", optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - diff --git a/12_exceptions_part1_groundwork/Makefile b/12_exceptions_part1_groundwork/Makefile deleted file mode 100644 index 5f49b1af5..000000000 --- a/12_exceptions_part1_groundwork/Makefile +++ /dev/null @@ -1,146 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot -DOCKER_ARG_DEV = --privileged -v /dev:/dev -DOCKER_ARG_NET = --network host - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) - DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) - DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -else - DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot jtagboot openocd gdb gdb-opt0 clippy \ - clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu: - @echo "This board is not yet supported for QEMU." -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -endif - -chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -jtagboot: - @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) - -openocd: - @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) - -define gen_gdb - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC) $1" $(RUSTC_CMD) - @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) -endef - -gdb: - $(call gen_gdb,-C debuginfo=2) - -gdb-opt0: - $(call gen_gdb,-C debuginfo=2 -C opt-level=0) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/12_exceptions_part1_groundwork/README.md b/12_exceptions_part1_groundwork/README.md deleted file mode 100644 index 04f20cd65..000000000 --- a/12_exceptions_part1_groundwork/README.md +++ /dev/null @@ -1,1023 +0,0 @@ -# Tutorial 12 - Exceptions Part 1: Groundwork - -## tl;dr - -- We lay the groundwork for all the architectural `CPU exceptions`. For now, only print an elaborate - system state through a `panic!` call, and halt execution -- This will help finding bugs during development and runtime. -- For demo purposes, MMU `page faults` are used to demonstrate (i) returning from an exception and - (ii) the default `panic!` behavior. - -## Table of Contents - -- [Introduction](#introduction) -- [Exception Types](#exception-types) -- [Exception entry](#exception-entry) - * [Exception Vectors](#exception-vectors) -- [Handler Code and Offsets](#handler-code-and-offsets) -- [Rust and Assembly Implementation](#rust-and-assembly-implementation) - * [Context Save and Restore](#context-save-and-restore) - * [Exception Vector Table](#exception-vector-table) - * [Implementing handlers](#implementing-handlers) -- [Causing an Exception - Testing the Code](#causing-an-exception---testing-the-code) -- [Test it](#test-it) -- [Diff to previous](#diff-to-previous) - -## Introduction - -Now that we are executing in `EL1`, and have activated the `MMU`, time is due for implementing `CPU -exceptions`. For now, we only set up a scaffold with very basic functionality that will help us to -find bugs along the way. A follow-up `Interrupt` tutorial in the future will continue the work we -start here. - -Please note that this tutorial is specific to the `AArch64` architecture. It does not contain any -generic exception handling code yet. - -## Exception Types - -In `AArch64`, it is differentiated between four types of exceptions. These are: -- Synchronous - - For example, a `data abort` (e.g. `page fault`) or a `system call`. They happen in direct - consequence of executing a certain instruction, hence _synchronously_. -- Interrupt Request (`IRQ`) - - For example, an external device, like a timer, is asserting a physical interrupt line. IRQs - happen _asynchronously_. -- Fast Interrupt Request (`FIQ`) - - These are basically interrupts that take priority over normal IRQs and have some more traits - that make them suitable to implement super-fast processing. However, this is out of scope for - this tutorial. For the sake of keeping these tutorials compact and concise, we will more or less - ignore FIQs and only implement a dummy handler that would halt the CPU core. -- System Error (`SError`) - - Like IRQs, SErrors happen asynchronously and are technically more or less the same. They are - intended to signal rather fatal errors in the system, e.g. if a transaction times out on the - `SoC` interconnect. They are very implementation specific and it is up to the SoC vendor to - decide which events are delivered as SErrors instead of normal IRQs. - -## Exception entry - -I recommend to read pages 1874-1876 of the [ARMv8 Architecture Reference Manual][ARMv8_Manual] to -understand the mechanisms of taking an exception. - -Here's an excerpt of important features for this tutorial: -- Exception entry moves the processor to the same or a higher `Exception Level`, but never to a - lower `EL`. -- The program status is saved in the `SPSR_ELx` register at the target `EL`. -- The preferred return address is saved in the `ELR_ELx` register. - - "Preferred" here means that `ELR_ELx` may hold the instruction address of the instructions that - caused the exception (`synchronous case`) or the first instruction that did not complete due to - an `asynchronous` exception. Details in Chapter D1.10.1 of the [ARMv8 Architecture Reference - Manual][ARMv8_Manual]. -- All kinds of exceptions are turned off upon taking an exception, so that by default, exception - handlers can not get interrupted themselves. -- Taking an exception will select the dedicated stack pointer of the target `EL`. - - For example, if an exception in `EL0` is taken, the Stack Pointer Select register `SPSel` will - switch from `0` to `1`, meaning that `SP_EL1` will be used by the exception vector code unless - you explicitly change it back to `SP_EL0`. - - -### Exception Vectors - -`AArch64` has a total of `16` exception vectors. There is one for each of the four kinds that were -introduced already, and additionally, it is taken into account _where_ the exception was taken from -and what the circumstances were. - -Here is a copy of the decision table as shown in Chapter D1.10.2 of the [ARMv8 Architecture -Reference Manual][ARMv8_Manual]: - -[ARMv8_Manual]: https://developer.arm.com/docs/ddi0487/latest/arm-architecture-reference-manual-armv8-for-armv8-a-architecture-profile - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exception taken from Offset for exception type
SynchronousIRQ or vIRQFIQ or vFIQSError or vSError
Current Exception level with SP_EL0.0x0000x0800x1000x180
Current Exception level with SP_ELx, x>0.0x2000x2800x3000x380
Lower Exception level, where the implemented level immediately lower than the target level is using AArch64.0x4000x4800x5000x580
Lower Exception level, where the implemented level immediately lower than the target level is using AArch32.0x6000x6800x7000x780
- -Since our kernel runs in `EL1`, using `SP_EL1`, if we'd cause a synchronous exception, the exception -vector at offset `0x200` would be executed. But what does that even mean? - -## Handler Code and Offsets - -In many architectures, Operating Systems register their exception handlers (aka vectors) by -compiling an architecturally defined data structure that stores function pointers to the different -handlers. This can be as simple as an ordinary array of function pointers. The `base address` of -this data structure is then stored into a special purpose register so that the CPU can branch to the -respective handler function upon taking an exception. The classic `x86_64` architecture follows this -principle, for example. - -In `AArch64`, it is a bit different. Here, we have the special purpose register as well, called -`VBAR_EL1`: Vector Base Address Register. - -However, it does not store the base address of an array of function pointers, but the base address -of a **memory location that contains code** for the 16 handlers, one handler back-to-back after the -other. Each handler can take a maximum space of `0x80` bytes, aka `128` bytes. That's why the table -above shows `offsets`: To indicate at which offset a certain handler starts. - -Of course, you are not obliged to cram all your handler code into only 128 bytes. You are free to -branch off to any other functions at any time. Actually, that is needed in most cases anyways, -because the context-saving code alone would take up most of the available space (you'll learn what -context saving is shortly). - -Additionally, there is a requirement that the `Vector Base Address` is aligned to `0x800` aka `2048` -bytes. - -## Rust and Assembly Implementation - -The implementation uses a mix of `Rust` and `Assembly` code. - -### Context Save and Restore - -Exception vectors, just like any other code, use a bunch of commonly shared processor resources. -Most of all, the set of `General Purpose Registers` (GPRs) that each core in `AArch64` provides -(`x0`-`x30`). - -In order to not taint these registers when executing exception vector code, it is general practice -to save these shared resources in memory (the stack, to be precise) as the very first action. This -is commonly described as *saving the context*. Exception vector code can then use the shared -resources in its own code without bothering, and as a last action before returning from exception -handling code, restore the context, so that the processor can continue where it left off before -taking the exception. - -Context save and restore is one of the few places in system software where it is strongly advised to -to use some hand-crafted assembly. Introducing `exception.S`: - -```asm -/// Call the function provided by parameter `\handler` after saving the exception context. Provide -/// the context as the first parameter to '\handler'. -.macro CALL_WITH_CONTEXT handler - // Make room on the stack for the exception context. - sub sp, sp, #16 * 17 - - // Store all general purpose registers on the stack. - stp x0, x1, [sp, #16 * 0] - stp x2, x3, [sp, #16 * 1] - stp x4, x5, [sp, #16 * 2] - stp x6, x7, [sp, #16 * 3] - stp x8, x9, [sp, #16 * 4] - stp x10, x11, [sp, #16 * 5] - stp x12, x13, [sp, #16 * 6] - stp x14, x15, [sp, #16 * 7] - stp x16, x17, [sp, #16 * 8] - stp x18, x19, [sp, #16 * 9] - stp x20, x21, [sp, #16 * 10] - stp x22, x23, [sp, #16 * 11] - stp x24, x25, [sp, #16 * 12] - stp x26, x27, [sp, #16 * 13] - stp x28, x29, [sp, #16 * 14] - - // Add the exception link register (ELR_EL1) and the saved program status (SPSR_EL1). - mrs x1, ELR_EL1 - mrs x2, SPSR_EL1 - - stp lr, x1, [sp, #16 * 15] - str w2, [sp, #16 * 16] - - // x0 is the first argument for the function called through `\handler`. - mov x0, sp - - // Call `\handler`. - bl \handler - - // After returning from exception handling code, replay the saved context and return via `eret`. - b __exception_restore_context -.endm -``` - -First, a macro for saving the context is defined. It eventually jumps to follow-up handler code, and -finally restores the context. In advance, we reserve space on the stack for the context. That is, -the 30 `GPRs`, the `link register`, the `saved program status` and the `exception link register` -(holding the preferred return address). Afterwards, we store those registers, save the current stack -address in `x0` and branch off to follow-up handler-code, whose function name is supplied as an -argument to the macro (`\handler`). - -The handler code will be written in Rust, but use the platform's `C` ABI. This way, we can define a -function signature that has a pointer to the context-data on the stack as its first argument, and -know that this argument is expected to be in the `x0` register. We need to use the `C` ABI here -because `Rust` has no stable convention ([yet](https://github.com/rust-lang/rfcs/issues/600)). - -### Exception Vector Table - -Next, we craft the exception vector table: - -```asm -.section .exception_vectors, "ax", @progbits - -// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. -.align 11 - -// Export a symbol for the Rust code to use. -__exception_vector_start: - -// Current exception level with SP_EL0. -// -// .org sets the offset relative to section start. -// -// # Safety -// -// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. -.org 0x000 - CALL_WITH_CONTEXT current_el0_synchronous -.org 0x080 - CALL_WITH_CONTEXT current_el0_irq -.org 0x100 - FIQ_SUSPEND -.org 0x180 - CALL_WITH_CONTEXT current_el0_serror - -// Current exception level with SP_ELx, x > 0. -.org 0x200 - CALL_WITH_CONTEXT current_elx_synchronous -.org 0x280 - CALL_WITH_CONTEXT current_elx_irq -.org 0x300 - FIQ_SUSPEND -.org 0x380 - CALL_WITH_CONTEXT current_elx_serror - -[...] -``` - -Note how each vector starts at the required offset from the section start using the `.org` -directive. Each macro call introduces an explicit handler function name, which is implemented in -`Rust` in `exception.rs`. - -### Implementing handlers - -The file `exception.rs` first defines a `struct` of the exception context that is stored on the -stack by the assembly code: - -```rust -/// The exception context as it is stored on the stack on exception entry. -#[repr(C)] -struct ExceptionContext { - /// General Purpose Registers. - gpr: [u64; 30], - - /// The link register, aka x30. - lr: u64, - - /// Exception link register. The program counter at the time the exception happened. - elr_el1: u64, - - /// Saved program status. - spsr_el1: SpsrEL1, -} -``` - -The handlers take a `struct ExceptionContext` argument. Since we do not plan to implement handlers -for each exception yet, a default handler is provided: - -```rust -/// Print verbose information about the exception and the panic. -fn default_exception_handler(e: &ExceptionContext) { - panic!( - "\n\nCPU Exception!\n\ - FAR_EL1: {:#018x}\n\ - {}\n\ - {}", - FAR_EL1.get(), - EsrEL1 {}, - e - ); -} -``` - -The actual handlers referenced from the assembly can now branch to it for the time being, e.g.: - -```rust -#[no_mangle] -unsafe extern "C" fn current_el0_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} -``` - -## Causing an Exception - Testing the Code - -We want to see two cases in action: -1. How taking, handling and returning from an exception works. -2. How the `panic!` print for unhandled exceptions looks like. - -So after setting up exceptions in `main.rs` by calling - -```rust -exception::handling_init(); -``` - -we cause a data abort exception by reading from memory address `8 GiB`: - -```rust -// Cause an exception by accessing a virtual address for which no translation was set up. This -// code accesses the address 8 GiB, which is outside the mapped address space. -// -// For demo purposes, the exception handler will catch the faulting 8 GiB address and allow -// execution to continue. -info!(""); -info!("Trying to write to address 8 GiB..."); -let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; -unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; -``` - -This triggers our exception code, because we try to read from a virtual address for which no mapping -has been installed. Remember, we only installed identity-mapped page tables for the first `1 GiB` -(RPi3) or `4 GiB` (RPi4) of address space in the previous tutorial. - -To survive this exception, the respective handler has a special demo case: - -```rust -#[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { - let far_el1 = FAR_EL1.get(); - - // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, - // advance the exception link register for one instruction, so that execution can continue. - if far_el1 == 8 * 1024 * 1024 * 1024 { - e.elr_el1 += 4; - - asm::eret() - } - - default_exception_handler(e); -} -``` - -It checks if the faulting address equals `8 GiB`, and if so, advances the copy of the `ELR` by 4, -which makes it point to the next instruction after the instruction that caused the exception. When -this handler returns, execution continues in the assembly macro we introduced before. The macro has -only one more line left: `b __exception_restore_context`, which jumps to an assembly function that -plays back our saved context before finally executing `eret` to return from the exception. - -This will kick us back into `main.rs`. But we also want to see the `panic!` print. - -Therefore, a second read is done, this time from address `9 GiB`. A case which the handler will not -catch, eventually triggering the `panic!` call from the default handler. - -## Test it - -Emphasis on the events at timestamps > `4.xxxxxx`. - -```console -$ make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 3 - -[ML] Requesting binary -[MP] ⏩ Pushing 64 KiB ========================================🦀 100% 32 KiB/s Time: 00:00:02 -[ML] Loaded! Executing the payload now - -[ 3.006343] Booting on: Raspberry Pi 3 -[ 3.007428] MMU online. Special regions: -[ 3.009339] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data -[ 3.013422] 0x3f000000 - 0x4000ffff | 16 MiB | Dev RW PXN | Device MMIO -[ 3.016985] Current privilege level: EL1 -[ 3.018895] Exception handling state: -[ 3.020676] Debug: Masked -[ 3.022240] SError: Masked -[ 3.023804] IRQ: Masked -[ 3.025368] FIQ: Masked -[ 3.026931] Architectural timer resolution: 52 ns -[ 3.029234] Drivers loaded: -[ 3.030580] 1. BCM GPIO -[ 3.032014] 2. BCM PL011 UART -[ 3.033708] Timer test, spinning for 1 second -[ 4.035837] -[ 4.035841] Trying to write to address 8 GiB... -[ 4.038006] ************************************************ -[ 4.040785] Whoa! We recovered from a synchronous exception! -[ 4.043565] ************************************************ -[ 4.046345] -[ 4.047040] Let's try again -[ 4.048387] Trying to write to address 9 GiB... - -Kernel panic: - -CPU Exception! -FAR_EL1: 0x0000000240000000 -ESR_EL1: 0x96000004 - Exception Class (EC) : 0x25 - Data Abort, current EL - Instr Specific Syndrome (ISS): 0x4 -ELR_EL1: 0x0000000000080db4 -SPSR_EL1: 0x600003c5 - Flags: - Negative (N): Not set - Zero (Z): Set - Carry (C): Set - Overflow (V): Not set - Exception handling state: - Debug (D): Masked - SError (A): Masked - IRQ (I): Masked - FIQ (F): Masked - Illegal Execution State (IL): Not set - -General purpose register: - x0 : 0x0000000000000000 x1 : 0x00000000000858f6 - x2 : 0x0000000000000026 x3 : 0x0000000000082a0c - x4 : 0x000000000007fc7c x5 : 0x0000000000000003 - x6 : 0x0000000000000000 x7 : 0x7f91bc052b2b0208 - x8 : 0x0000000240000000 x9 : 0x00000000000858f6 - x10: 0x000000000000041d x11: 0x000000003f201000 - x12: 0x0000000000000019 x13: 0x000000000007fc7d - x14: 0x000000000007fdc8 x15: 0x0000000000000040 - x16: 0x0000000000000000 x17: 0x0000000000000040 - x18: 0x9e06782800000028 x19: 0x000000003b9aca00 - x20: 0x00000000000003e8 x21: 0x0000000000082f58 - x22: 0x00000000000830cc x23: 0x0000000000090008 - x24: 0x00000000000f4240 x25: 0x0000000000085248 - x26: 0x00000000000856e0 x27: 0x00000000000857c0 - x28: 0x00000000000830cc x29: 0x0000000000085530 - lr : 0x0000000000080da8 -``` - -## Diff to previous -```diff - -diff -uNr 11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs ---- 11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs -+++ 12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs -@@ -4,7 +4,230 @@ - - //! Architectural synchronous and asynchronous exception handling. - --use cortex_a::regs::*; -+use core::{cell::UnsafeCell, fmt}; -+use cortex_a::{asm, barrier, regs::*}; -+use register::InMemoryRegister; -+ -+// Assembly counterpart to this file. -+global_asm!(include_str!("exception.S")); -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Wrapper struct for memory copy of SPSR_EL1. -+#[repr(transparent)] -+struct SpsrEL1(InMemoryRegister); -+ -+/// The exception context as it is stored on the stack on exception entry. -+#[repr(C)] -+struct ExceptionContext { -+ /// General Purpose Registers. -+ gpr: [u64; 30], -+ -+ /// The link register, aka x30. -+ lr: u64, -+ -+ /// Exception link register. The program counter at the time the exception happened. -+ elr_el1: u64, -+ -+ /// Saved program status. -+ spsr_el1: SpsrEL1, -+} -+ -+/// Wrapper struct for pretty printing ESR_EL1. -+struct EsrEL1; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Prints verbose information about the exception and then panics. -+fn default_exception_handler(e: &ExceptionContext) { -+ panic!( -+ "\n\nCPU Exception!\n\ -+ FAR_EL1: {:#018x}\n\ -+ {}\n\ -+ {}", -+ FAR_EL1.get(), -+ EsrEL1 {}, -+ e -+ ); -+} -+ -+//------------------------------------------------------------------------------ -+// Current, EL0 -+//------------------------------------------------------------------------------ -+ -+#[no_mangle] -+unsafe extern "C" fn current_el0_synchronous(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+#[no_mangle] -+unsafe extern "C" fn current_el0_irq(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+#[no_mangle] -+unsafe extern "C" fn current_el0_serror(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+//------------------------------------------------------------------------------ -+// Current, ELx -+//------------------------------------------------------------------------------ -+ -+#[no_mangle] -+unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { -+ let far_el1 = FAR_EL1.get(); -+ -+ // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, -+ // advance the exception link register for one instruction, so that execution can continue. -+ if far_el1 == 8 * 1024 * 1024 * 1024 { -+ e.elr_el1 += 4; -+ -+ asm::eret() -+ } -+ -+ default_exception_handler(e); -+} -+ -+#[no_mangle] -+unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+#[no_mangle] -+unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+//------------------------------------------------------------------------------ -+// Lower, AArch64 -+//------------------------------------------------------------------------------ -+ -+#[no_mangle] -+unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+#[no_mangle] -+unsafe extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+#[no_mangle] -+unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+//------------------------------------------------------------------------------ -+// Lower, AArch32 -+//------------------------------------------------------------------------------ -+ -+#[no_mangle] -+unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+#[no_mangle] -+unsafe extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+#[no_mangle] -+unsafe extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { -+ default_exception_handler(e); -+} -+ -+//------------------------------------------------------------------------------ -+// Pretty printing -+//------------------------------------------------------------------------------ -+ -+/// Human readable ESR_EL1. -+#[rustfmt::skip] -+impl fmt::Display for EsrEL1 { -+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -+ let esr_el1 = ESR_EL1.extract(); -+ -+ // Raw print of whole register. -+ writeln!(f, "ESR_EL1: {:#010x}", esr_el1.get())?; -+ -+ // Raw print of exception class. -+ write!(f, " Exception Class (EC) : {:#x}", esr_el1.read(ESR_EL1::EC))?; -+ -+ // Exception class, translation. -+ let ec_translation = match esr_el1.read_as_enum(ESR_EL1::EC) { -+ Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", -+ _ => "N/A", -+ }; -+ writeln!(f, " - {}", ec_translation)?; -+ -+ // Raw print of instruction specific syndrome. -+ write!(f, " Instr Specific Syndrome (ISS): {:#x}", esr_el1.read(ESR_EL1::ISS))?; -+ -+ Ok(()) -+ } -+} -+ -+/// Human readable SPSR_EL1. -+#[rustfmt::skip] -+impl fmt::Display for SpsrEL1 { -+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -+ // Raw value. -+ writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; -+ -+ let to_flag_str = |x| -> _ { -+ if x { "Set" } else { "Not set" } -+ }; -+ -+ writeln!(f, " Flags:")?; -+ writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; -+ writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; -+ writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; -+ writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; -+ -+ let to_mask_str = |x| -> _ { -+ if x { "Masked" } else { "Unmasked" } -+ }; -+ -+ writeln!(f, " Exception handling state:")?; -+ writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; -+ writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; -+ writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; -+ writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; -+ -+ write!(f, " Illegal Execution State (IL): {}", -+ to_flag_str(self.0.is_set(SPSR_EL1::IL)) -+ )?; -+ -+ Ok(()) -+ } -+} -+ -+/// Human readable print of the exception context. -+impl fmt::Display for ExceptionContext { -+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -+ writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; -+ writeln!(f, "{}", self.spsr_el1)?; -+ writeln!(f)?; -+ writeln!(f, "General purpose register:")?; -+ -+ #[rustfmt::skip] -+ let alternating = |x| -> _ { -+ if x modulo 2 == 0 { " " } else { "\n" } -+ }; -+ -+ // Print two registers per line. -+ for (i, reg) in self.gpr.iter().enumerate() { -+ write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; -+ } -+ write!(f, " lr : {:#018x}", self.lr)?; -+ -+ Ok(()) -+ } -+} - - //-------------------------------------------------------------------------------------------------- - // Public Code -@@ -21,3 +244,23 @@ - _ => (PrivilegeLevel::Unknown, "Unknown"), - } - } -+ -+/// Init exception handling by setting the exception vector base address register. -+/// -+/// # Safety -+/// -+/// - Changes the HW state of the executing core. -+/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must -+/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference -+/// Manual. -+pub unsafe fn handling_init() { -+ // Provided by exception.S. -+ extern "Rust" { -+ static __exception_vector_start: UnsafeCell<()>; -+ } -+ -+ VBAR_EL1.set(__exception_vector_start.get() as u64); -+ -+ // Force VBAR update to complete before next instruction. -+ barrier::isb(barrier::SY); -+} - -diff -uNr 11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.S 12_exceptions_part1_groundwork/src/_arch/aarch64/exception.S ---- 11_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.S -+++ 12_exceptions_part1_groundwork/src/_arch/aarch64/exception.S -@@ -0,0 +1,138 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+/// Call the function provided by parameter `\handler` after saving the exception context. Provide -+/// the context as the first parameter to '\handler'. -+.macro CALL_WITH_CONTEXT handler -+ // Make room on the stack for the exception context. -+ sub sp, sp, #16 * 17 -+ -+ // Store all general purpose registers on the stack. -+ stp x0, x1, [sp, #16 * 0] -+ stp x2, x3, [sp, #16 * 1] -+ stp x4, x5, [sp, #16 * 2] -+ stp x6, x7, [sp, #16 * 3] -+ stp x8, x9, [sp, #16 * 4] -+ stp x10, x11, [sp, #16 * 5] -+ stp x12, x13, [sp, #16 * 6] -+ stp x14, x15, [sp, #16 * 7] -+ stp x16, x17, [sp, #16 * 8] -+ stp x18, x19, [sp, #16 * 9] -+ stp x20, x21, [sp, #16 * 10] -+ stp x22, x23, [sp, #16 * 11] -+ stp x24, x25, [sp, #16 * 12] -+ stp x26, x27, [sp, #16 * 13] -+ stp x28, x29, [sp, #16 * 14] -+ -+ // Add the exception link register (ELR_EL1) and the saved program status (SPSR_EL1). -+ mrs x1, ELR_EL1 -+ mrs x2, SPSR_EL1 -+ -+ stp lr, x1, [sp, #16 * 15] -+ str x2, [sp, #16 * 16] -+ -+ // x0 is the first argument for the function called through `\handler`. -+ mov x0, sp -+ -+ // Call `\handler`. -+ bl \handler -+ -+ // After returning from exception handling code, replay the saved context and return via `eret`. -+ b __exception_restore_context -+.endm -+ -+.macro FIQ_SUSPEND -+1: wfe -+ b 1b -+.endm -+ -+//-------------------------------------------------------------------------------------------------- -+// The exception vector table. -+//-------------------------------------------------------------------------------------------------- -+.section .exception_vectors, "ax", @progbits -+ -+// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. -+.align 11 -+ -+// Export a symbol for the Rust code to use. -+__exception_vector_start: -+ -+// Current exception level with SP_EL0. -+// -+// .org sets the offset relative to section start. -+// -+// # Safety -+// -+// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. -+.org 0x000 -+ CALL_WITH_CONTEXT current_el0_synchronous -+.org 0x080 -+ CALL_WITH_CONTEXT current_el0_irq -+.org 0x100 -+ FIQ_SUSPEND -+.org 0x180 -+ CALL_WITH_CONTEXT current_el0_serror -+ -+// Current exception level with SP_ELx, x > 0. -+.org 0x200 -+ CALL_WITH_CONTEXT current_elx_synchronous -+.org 0x280 -+ CALL_WITH_CONTEXT current_elx_irq -+.org 0x300 -+ FIQ_SUSPEND -+.org 0x380 -+ CALL_WITH_CONTEXT current_elx_serror -+ -+// Lower exception level, AArch64 -+.org 0x400 -+ CALL_WITH_CONTEXT lower_aarch64_synchronous -+.org 0x480 -+ CALL_WITH_CONTEXT lower_aarch64_irq -+.org 0x500 -+ FIQ_SUSPEND -+.org 0x580 -+ CALL_WITH_CONTEXT lower_aarch64_serror -+ -+// Lower exception level, AArch32 -+.org 0x600 -+ CALL_WITH_CONTEXT lower_aarch32_synchronous -+.org 0x680 -+ CALL_WITH_CONTEXT lower_aarch32_irq -+.org 0x700 -+ FIQ_SUSPEND -+.org 0x780 -+ CALL_WITH_CONTEXT lower_aarch32_serror -+.org 0x800 -+ -+//-------------------------------------------------------------------------------------------------- -+// Helper functions -+//-------------------------------------------------------------------------------------------------- -+.section .text -+ -+__exception_restore_context: -+ ldr w19, [sp, #16 * 16] -+ ldp lr, x20, [sp, #16 * 15] -+ -+ msr SPSR_EL1, x19 -+ msr ELR_EL1, x20 -+ -+ ldp x0, x1, [sp, #16 * 0] -+ ldp x2, x3, [sp, #16 * 1] -+ ldp x4, x5, [sp, #16 * 2] -+ ldp x6, x7, [sp, #16 * 3] -+ ldp x8, x9, [sp, #16 * 4] -+ ldp x10, x11, [sp, #16 * 5] -+ ldp x12, x13, [sp, #16 * 6] -+ ldp x14, x15, [sp, #16 * 7] -+ ldp x16, x17, [sp, #16 * 8] -+ ldp x18, x19, [sp, #16 * 9] -+ ldp x20, x21, [sp, #16 * 10] -+ ldp x22, x23, [sp, #16 * 11] -+ ldp x24, x25, [sp, #16 * 12] -+ ldp x26, x27, [sp, #16 * 13] -+ ldp x28, x29, [sp, #16 * 14] -+ -+ add sp, sp, #16 * 17 -+ -+ eret - -diff -uNr 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld 12_exceptions_part1_groundwork/src/bsp/raspberrypi/link.ld ---- 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld -+++ 12_exceptions_part1_groundwork/src/bsp/raspberrypi/link.ld -@@ -14,6 +14,11 @@ - *(.text._start) *(.text*) - } - -+ .exception_vectors : -+ { -+ *(.exception_vectors*) -+ } -+ - .rodata : - { - *(.rodata*) - -diff -uNr 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs 12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs ---- 11_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs -+++ 12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs -@@ -12,7 +12,7 @@ - // Public Definitions - //-------------------------------------------------------------------------------------------------- - --const NUM_MEM_RANGES: usize = 3; -+const NUM_MEM_RANGES: usize = 2; - - /// The virtual memory layout. - /// -@@ -32,16 +32,6 @@ - }, - }, - TranslationDescriptor { -- name: "Remapped Device MMIO", -- virtual_range: remapped_mmio_range_inclusive, -- physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), -- attribute_fields: AttributeFields { -- mem_attributes: MemAttributes::Device, -- acc_perms: AccessPermissions::ReadWrite, -- execute_never: true, -- }, -- }, -- TranslationDescriptor { - name: "Device MMIO", - virtual_range: mmio_range_inclusive, - physical_range_translation: Translation::Identity, -@@ -64,11 +54,6 @@ - RangeInclusive::new(super::ro_start(), super::ro_end() - 1) - } - --fn remapped_mmio_range_inclusive() -> RangeInclusive { -- // The last 64 KiB slot in the first 512 MiB -- RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) --} -- - fn mmio_range_inclusive() -> RangeInclusive { - RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) - } - -diff -uNr 11_virtual_mem_part1_identity_mapping/src/bsp.rs 12_exceptions_part1_groundwork/src/bsp.rs ---- 11_virtual_mem_part1_identity_mapping/src/bsp.rs -+++ 12_exceptions_part1_groundwork/src/bsp.rs -@@ -4,7 +4,7 @@ - - //! Conditional re-exporting of Board Support Packages. - --pub mod device_driver; -+mod device_driver; - - #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] - mod raspberrypi; - -diff -uNr 11_virtual_mem_part1_identity_mapping/src/main.rs 12_exceptions_part1_groundwork/src/main.rs ---- 11_virtual_mem_part1_identity_mapping/src/main.rs -+++ 12_exceptions_part1_groundwork/src/main.rs -@@ -109,6 +109,7 @@ - #![feature(const_generics)] - #![feature(const_panic)] - #![feature(format_args_nl)] -+#![feature(global_asm)] - #![feature(naked_functions)] - #![feature(panic_info_message)] - #![feature(trait_alias)] -@@ -144,6 +145,8 @@ - use driver::interface::DriverManager; - use memory::mmu::interface::MMU; - -+ exception::handling_init(); -+ - if let Err(string) = memory::mmu::mmu().init() { - panic!("MMU: {}", string); - } -@@ -195,13 +198,28 @@ - info!("Timer test, spinning for 1 second"); - time::time_manager().spin_for(Duration::from_secs(1)); - -- let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; -- writeln!( -- remapped_uart, -- "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" -- ) -- .unwrap(); -+ // Cause an exception by accessing a virtual address for which no translation was set up. This -+ // code accesses the address 8 GiB, which is outside the mapped address space. -+ // -+ // For demo purposes, the exception handler will catch the faulting 8 GiB address and allow -+ // execution to continue. -+ info!(""); -+ info!("Trying to write to address 8 GiB..."); -+ let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; -+ unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; -+ -+ info!("************************************************"); -+ info!("Whoa! We recovered from a synchronous exception!"); -+ info!("************************************************"); -+ info!(""); -+ info!("Let's try again"); -+ -+ // Now use address 9 GiB. The exception handler won't forgive us this time. -+ info!("Trying to write to address 9 GiB..."); -+ big_addr = 9 * 1024 * 1024 * 1024; -+ unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; - -+ // Will never reach here in this tutorial. - info!("Echoing input now"); - loop { - let c = bsp::console::console().read_char(); - -diff -uNr 11_virtual_mem_part1_identity_mapping/src/memory/mmu.rs 12_exceptions_part1_groundwork/src/memory/mmu.rs ---- 11_virtual_mem_part1_identity_mapping/src/memory/mmu.rs -+++ 12_exceptions_part1_groundwork/src/memory/mmu.rs -@@ -42,6 +42,7 @@ - - /// Architecture agnostic translation types. - #[allow(missing_docs)] -+#[allow(dead_code)] - #[derive(Copy, Clone)] - pub enum Translation { - Identity, - -``` diff --git a/12_exceptions_part1_groundwork/build.rs b/12_exceptions_part1_groundwork/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/12_exceptions_part1_groundwork/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/12_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs b/12_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 3e5e57530..000000000 --- a/12_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - // Expect the boot core to start in EL2. - if (bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id()) - && (CurrentEL.get() == CurrentEL::EL::EL2.value) - { - el2_to_el1_transition() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -/// Transition from EL2 to EL1. -/// -/// # Safety -/// -/// - The HW state of EL1 must be prepared in a sound way. -/// - Exception return from EL2 must must continue execution in EL1 with -/// `runtime_init::runtime_init()`. -#[inline(always)] -unsafe fn el2_to_el1_transition() -> ! { - use crate::runtime_init; - - // Enable timer counter registers for EL1. - CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); - - // No offset for reading the counters. - CNTVOFF_EL2.set(0); - - // Set EL1 execution state to AArch64. - HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); - - // Set up a simulated exception return. - // - // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a - // stack pointer. - SPSR_EL2.write( - SPSR_EL2::D::Masked - + SPSR_EL2::A::Masked - + SPSR_EL2::I::Masked - + SPSR_EL2::F::Masked - + SPSR_EL2::M::EL1h, - ); - - // Second, let the link register point to runtime_init(). - ELR_EL2.set(runtime_init::runtime_init as *const () as u64); - - // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. - SP_EL1.set(bsp::memory::boot_core_stack_end() as u64); - - // Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. - asm::eret() -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} diff --git a/12_exceptions_part1_groundwork/src/_arch/aarch64/cpu/smp.rs b/12_exceptions_part1_groundwork/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/12_exceptions_part1_groundwork/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/12_exceptions_part1_groundwork/src/_arch/aarch64/exception.S b/12_exceptions_part1_groundwork/src/_arch/aarch64/exception.S deleted file mode 100644 index ee3b5497e..000000000 --- a/12_exceptions_part1_groundwork/src/_arch/aarch64/exception.S +++ /dev/null @@ -1,138 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -/// Call the function provided by parameter `\handler` after saving the exception context. Provide -/// the context as the first parameter to '\handler'. -.macro CALL_WITH_CONTEXT handler - // Make room on the stack for the exception context. - sub sp, sp, #16 * 17 - - // Store all general purpose registers on the stack. - stp x0, x1, [sp, #16 * 0] - stp x2, x3, [sp, #16 * 1] - stp x4, x5, [sp, #16 * 2] - stp x6, x7, [sp, #16 * 3] - stp x8, x9, [sp, #16 * 4] - stp x10, x11, [sp, #16 * 5] - stp x12, x13, [sp, #16 * 6] - stp x14, x15, [sp, #16 * 7] - stp x16, x17, [sp, #16 * 8] - stp x18, x19, [sp, #16 * 9] - stp x20, x21, [sp, #16 * 10] - stp x22, x23, [sp, #16 * 11] - stp x24, x25, [sp, #16 * 12] - stp x26, x27, [sp, #16 * 13] - stp x28, x29, [sp, #16 * 14] - - // Add the exception link register (ELR_EL1) and the saved program status (SPSR_EL1). - mrs x1, ELR_EL1 - mrs x2, SPSR_EL1 - - stp lr, x1, [sp, #16 * 15] - str x2, [sp, #16 * 16] - - // x0 is the first argument for the function called through `\handler`. - mov x0, sp - - // Call `\handler`. - bl \handler - - // After returning from exception handling code, replay the saved context and return via `eret`. - b __exception_restore_context -.endm - -.macro FIQ_SUSPEND -1: wfe - b 1b -.endm - -//-------------------------------------------------------------------------------------------------- -// The exception vector table. -//-------------------------------------------------------------------------------------------------- -.section .exception_vectors, "ax", @progbits - -// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. -.align 11 - -// Export a symbol for the Rust code to use. -__exception_vector_start: - -// Current exception level with SP_EL0. -// -// .org sets the offset relative to section start. -// -// # Safety -// -// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. -.org 0x000 - CALL_WITH_CONTEXT current_el0_synchronous -.org 0x080 - CALL_WITH_CONTEXT current_el0_irq -.org 0x100 - FIQ_SUSPEND -.org 0x180 - CALL_WITH_CONTEXT current_el0_serror - -// Current exception level with SP_ELx, x > 0. -.org 0x200 - CALL_WITH_CONTEXT current_elx_synchronous -.org 0x280 - CALL_WITH_CONTEXT current_elx_irq -.org 0x300 - FIQ_SUSPEND -.org 0x380 - CALL_WITH_CONTEXT current_elx_serror - -// Lower exception level, AArch64 -.org 0x400 - CALL_WITH_CONTEXT lower_aarch64_synchronous -.org 0x480 - CALL_WITH_CONTEXT lower_aarch64_irq -.org 0x500 - FIQ_SUSPEND -.org 0x580 - CALL_WITH_CONTEXT lower_aarch64_serror - -// Lower exception level, AArch32 -.org 0x600 - CALL_WITH_CONTEXT lower_aarch32_synchronous -.org 0x680 - CALL_WITH_CONTEXT lower_aarch32_irq -.org 0x700 - FIQ_SUSPEND -.org 0x780 - CALL_WITH_CONTEXT lower_aarch32_serror -.org 0x800 - -//-------------------------------------------------------------------------------------------------- -// Helper functions -//-------------------------------------------------------------------------------------------------- -.section .text - -__exception_restore_context: - ldr w19, [sp, #16 * 16] - ldp lr, x20, [sp, #16 * 15] - - msr SPSR_EL1, x19 - msr ELR_EL1, x20 - - ldp x0, x1, [sp, #16 * 0] - ldp x2, x3, [sp, #16 * 1] - ldp x4, x5, [sp, #16 * 2] - ldp x6, x7, [sp, #16 * 3] - ldp x8, x9, [sp, #16 * 4] - ldp x10, x11, [sp, #16 * 5] - ldp x12, x13, [sp, #16 * 6] - ldp x14, x15, [sp, #16 * 7] - ldp x16, x17, [sp, #16 * 8] - ldp x18, x19, [sp, #16 * 9] - ldp x20, x21, [sp, #16 * 10] - ldp x22, x23, [sp, #16 * 11] - ldp x24, x25, [sp, #16 * 12] - ldp x26, x27, [sp, #16 * 13] - ldp x28, x29, [sp, #16 * 14] - - add sp, sp, #16 * 17 - - eret diff --git a/12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs b/12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs deleted file mode 100644 index d932445c3..000000000 --- a/12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs +++ /dev/null @@ -1,266 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural synchronous and asynchronous exception handling. - -use core::{cell::UnsafeCell, fmt}; -use cortex_a::{asm, barrier, regs::*}; -use register::InMemoryRegister; - -// Assembly counterpart to this file. -global_asm!(include_str!("exception.S")); - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Wrapper struct for memory copy of SPSR_EL1. -#[repr(transparent)] -struct SpsrEL1(InMemoryRegister); - -/// The exception context as it is stored on the stack on exception entry. -#[repr(C)] -struct ExceptionContext { - /// General Purpose Registers. - gpr: [u64; 30], - - /// The link register, aka x30. - lr: u64, - - /// Exception link register. The program counter at the time the exception happened. - elr_el1: u64, - - /// Saved program status. - spsr_el1: SpsrEL1, -} - -/// Wrapper struct for pretty printing ESR_EL1. -struct EsrEL1; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Prints verbose information about the exception and then panics. -fn default_exception_handler(e: &ExceptionContext) { - panic!( - "\n\nCPU Exception!\n\ - FAR_EL1: {:#018x}\n\ - {}\n\ - {}", - FAR_EL1.get(), - EsrEL1 {}, - e - ); -} - -//------------------------------------------------------------------------------ -// Current, EL0 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn current_el0_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_el0_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_el0_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Current, ELx -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { - let far_el1 = FAR_EL1.get(); - - // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, - // advance the exception link register for one instruction, so that execution can continue. - if far_el1 == 8 * 1024 * 1024 * 1024 { - e.elr_el1 += 4; - - asm::eret() - } - - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Lower, AArch64 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Lower, AArch32 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Pretty printing -//------------------------------------------------------------------------------ - -/// Human readable ESR_EL1. -#[rustfmt::skip] -impl fmt::Display for EsrEL1 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let esr_el1 = ESR_EL1.extract(); - - // Raw print of whole register. - writeln!(f, "ESR_EL1: {:#010x}", esr_el1.get())?; - - // Raw print of exception class. - write!(f, " Exception Class (EC) : {:#x}", esr_el1.read(ESR_EL1::EC))?; - - // Exception class, translation. - let ec_translation = match esr_el1.read_as_enum(ESR_EL1::EC) { - Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", - _ => "N/A", - }; - writeln!(f, " - {}", ec_translation)?; - - // Raw print of instruction specific syndrome. - write!(f, " Instr Specific Syndrome (ISS): {:#x}", esr_el1.read(ESR_EL1::ISS))?; - - Ok(()) - } -} - -/// Human readable SPSR_EL1. -#[rustfmt::skip] -impl fmt::Display for SpsrEL1 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Raw value. - writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; - - let to_flag_str = |x| -> _ { - if x { "Set" } else { "Not set" } - }; - - writeln!(f, " Flags:")?; - writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; - writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; - writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; - writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - writeln!(f, " Exception handling state:")?; - writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; - writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; - writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; - writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; - - write!(f, " Illegal Execution State (IL): {}", - to_flag_str(self.0.is_set(SPSR_EL1::IL)) - )?; - - Ok(()) - } -} - -/// Human readable print of the exception context. -impl fmt::Display for ExceptionContext { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; - writeln!(f, "{}", self.spsr_el1)?; - writeln!(f)?; - writeln!(f, "General purpose register:")?; - - #[rustfmt::skip] - let alternating = |x| -> _ { - if x % 2 == 0 { " " } else { "\n" } - }; - - // Print two registers per line. - for (i, reg) in self.gpr.iter().enumerate() { - write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; - } - write!(f, " lr : {:#018x}", self.lr)?; - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use crate::exception::PrivilegeLevel; - -/// The processing element's current privilege level. -pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { - let el = CurrentEL.read_as_enum(CurrentEL::EL); - match el { - Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), - Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), - Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), - _ => (PrivilegeLevel::Unknown, "Unknown"), - } -} - -/// Init exception handling by setting the exception vector base address register. -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must -/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference -/// Manual. -pub unsafe fn handling_init() { - // Provided by exception.S. - extern "Rust" { - static __exception_vector_start: UnsafeCell<()>; - } - - VBAR_EL1.set(__exception_vector_start.get() as u64); - - // Force VBAR update to complete before next instruction. - barrier::isb(barrier::SY); -} diff --git a/12_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs b/12_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs deleted file mode 100644 index f660544c1..000000000 --- a/12_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural asynchronous exception handling. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -trait DaifField { - fn daif_field() -> register::Field; -} - -struct Debug; -struct SError; -struct IRQ; -struct FIQ; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl DaifField for Debug { - fn daif_field() -> register::Field { - DAIF::D - } -} - -impl DaifField for SError { - fn daif_field() -> register::Field { - DAIF::A - } -} - -impl DaifField for IRQ { - fn daif_field() -> register::Field { - DAIF::I - } -} - -impl DaifField for FIQ { - fn daif_field() -> register::Field { - DAIF::F - } -} - -fn is_masked() -> bool -where - T: DaifField, -{ - DAIF.is_set(T::daif_field()) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Print the AArch64 exceptions status. -#[rustfmt::skip] -pub fn print_state() { - use crate::info; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - info!(" Debug: {}", to_mask_str(is_masked::())); - info!(" SError: {}", to_mask_str(is_masked::())); - info!(" IRQ: {}", to_mask_str(is_masked::())); - info!(" FIQ: {}", to_mask_str(is_masked::())); -} diff --git a/12_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs b/12_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs deleted file mode 100644 index ff653a091..000000000 --- a/12_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs +++ /dev/null @@ -1,333 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management Unit Driver. -//! -//! Static translation tables, compiled on boot; Everything 64 KiB granule. - -use super::{AccessPermissions, AttributeFields, MemAttributes}; -use crate::{bsp, memory}; -use core::convert; -use cortex_a::{barrier, regs::*}; -use register::{register_bitfields, InMemoryRegister}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. -register_bitfields! {u64, - STAGE1_TABLE_DESCRIPTOR [ - /// Physical address of the next descriptor. - NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. -register_bitfields! {u64, - STAGE1_PAGE_DESCRIPTOR [ - /// Privileged execute-never. - PXN OFFSET(53) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). - OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - /// Access flag. - AF OFFSET(10) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Shareability field. - SH OFFSET(8) NUMBITS(2) [ - OuterShareable = 0b10, - InnerShareable = 0b11 - ], - - /// Access Permissions. - AP OFFSET(6) NUMBITS(2) [ - RW_EL1 = 0b00, - RW_EL1_EL0 = 0b01, - RO_EL1 = 0b10, - RO_EL1_EL0 = 0b11 - ], - - /// Memory attributes index into the MAIR_EL1 register. - AttrIndx OFFSET(2) NUMBITS(3) [], - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -const SIXTYFOUR_KIB_SHIFT: usize = 16; // log2(64 * 1024) -const FIVETWELVE_MIB_SHIFT: usize = 29; // log2(512 * 1024 * 1024) - -/// A table descriptor for 64 KiB aperture. -/// -/// The output points to the next table. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct TableDescriptor(u64); - -/// A page descriptor with 64 KiB aperture. -/// -/// The output points to physical memory. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct PageDescriptor(u64); - -/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB -/// aligned, hence the "reverse" order of appearance. -#[repr(C)] -#[repr(align(65536))] -struct FixedSizeTranslationTable { - /// Page descriptors, covering 64 KiB windows per entry. - lvl3: [[PageDescriptor; 8192]; NUM_TABLES], - - /// Table descriptors, covering 512 MiB windows. - lvl2: [TableDescriptor; NUM_TABLES], -} - -/// Usually evaluates to 1 GiB for RPi3 and 4 GiB for RPi 4. -const NUM_LVL2_TABLES: usize = bsp::memory::mmu::addr_space_size() >> FIVETWELVE_MIB_SHIFT; -type ArchTranslationTable = FixedSizeTranslationTable; - -trait BaseAddr { - fn base_addr_u64(&self) -> u64; - fn base_addr_usize(&self) -> usize; -} - -/// Constants for indexing the MAIR_EL1. -#[allow(dead_code)] -mod mair { - pub const DEVICE: u64 = 0; - pub const NORMAL: u64 = 1; -} - -/// Memory Management Unit type. -struct MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -/// The translation tables. -/// -/// # Safety -/// -/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". -static mut KERNEL_TABLES: ArchTranslationTable = ArchTranslationTable::new(); - -static MMU: MemoryManagementUnit = MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl BaseAddr for [T; N] { - fn base_addr_u64(&self) -> u64 { - self as *const T as u64 - } - - fn base_addr_usize(&self) -> usize { - self as *const _ as usize - } -} - -impl convert::From for TableDescriptor { - fn from(next_lvl_table_addr: usize) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = next_lvl_table_addr >> SIXTYFOUR_KIB_SHIFT; - val.write( - STAGE1_TABLE_DESCRIPTOR::VALID::True - + STAGE1_TABLE_DESCRIPTOR::TYPE::Table - + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64), - ); - - TableDescriptor(val.get()) - } -} - -/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. -impl convert::From - for register::FieldValue -{ - fn from(attribute_fields: AttributeFields) -> Self { - // Memory attributes. - let mut desc = match attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => { - STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::NORMAL) - } - MemAttributes::Device => { - STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::DEVICE) - } - }; - - // Access Permissions. - desc += match attribute_fields.acc_perms { - AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, - AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, - }; - - // Execute Never. - desc += if attribute_fields.execute_never { - STAGE1_PAGE_DESCRIPTOR::PXN::True - } else { - STAGE1_PAGE_DESCRIPTOR::PXN::False - }; - - desc - } -} - -impl PageDescriptor { - /// Create an instance. - fn new(output_addr: usize, attribute_fields: AttributeFields) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = output_addr as u64 >> SIXTYFOUR_KIB_SHIFT; - val.write( - STAGE1_PAGE_DESCRIPTOR::VALID::True - + STAGE1_PAGE_DESCRIPTOR::AF::True - + attribute_fields.into() - + STAGE1_PAGE_DESCRIPTOR::TYPE::Table - + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted), - ); - - Self(val.get()) - } -} - -impl FixedSizeTranslationTable<{ NUM_TABLES }> { - /// Create an instance. - pub const fn new() -> Self { - assert!(NUM_TABLES > 0); - - Self { - lvl3: [[PageDescriptor(0); 8192]; NUM_TABLES], - lvl2: [TableDescriptor(0); NUM_TABLES], - } - } -} - -/// Setup function for the MAIR_EL1 register. -fn set_up_mair() { - // Define the memory types being mapped. - MAIR_EL1.write( - // Attribute 1 - Cacheable normal DRAM. - MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + - MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + - - // Attribute 0 - Device. - MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, - ); -} - -/// Iterates over all static translation table entries and fills them at once. -/// -/// # Safety -/// -/// - Modifies a `static mut`. Ensure it only happens from here. -unsafe fn populate_tt_entries() -> Result<(), &'static str> { - for (l2_nr, l2_entry) in KERNEL_TABLES.lvl2.iter_mut().enumerate() { - *l2_entry = KERNEL_TABLES.lvl3[l2_nr].base_addr_usize().into(); - - for (l3_nr, l3_entry) in KERNEL_TABLES.lvl3[l2_nr].iter_mut().enumerate() { - let virt_addr = (l2_nr << FIVETWELVE_MIB_SHIFT) + (l3_nr << SIXTYFOUR_KIB_SHIFT); - - let (output_addr, attribute_fields) = - bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; - - *l3_entry = PageDescriptor::new(output_addr, attribute_fields); - } - } - - Ok(()) -} - -/// Configure various settings of stage 1 of the EL1 translation regime. -fn configure_translation_control() { - let ips = ID_AA64MMFR0_EL1.read(ID_AA64MMFR0_EL1::PARange); - - TCR_EL1.write( - TCR_EL1::TBI0::Ignored - + TCR_EL1::IPS.val(ips) - + TCR_EL1::TG0::KiB_64 - + TCR_EL1::SH0::Inner - + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::EPD0::EnableTTBR0Walks - + TCR_EL1::T0SZ.val(32), // TTBR0 spans 4 GiB total. - ); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the MMU instance. -pub fn mmu() -> &'static impl memory::mmu::interface::MMU { - &MMU -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl memory::mmu::interface::MMU for MemoryManagementUnit { - unsafe fn init(&self) -> Result<(), &'static str> { - // Fail early if translation granule is not supported. Both RPis support it, though. - if !ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported) { - return Err("Translation granule not supported in HW"); - } - - // Prepare the memory attribute indirection register. - set_up_mair(); - - // Populate translation tables. - populate_tt_entries()?; - - // Set the "Translation Table Base Register". - TTBR0_EL1.set_baddr(KERNEL_TABLES.lvl2.base_addr_u64()); - - configure_translation_control(); - - // Switch the MMU on. - // - // First, force all previous changes to be seen before the MMU is enabled. - barrier::isb(barrier::SY); - - // Enable the MMU and turn on data and instruction caching. - SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); - - // Force MMU init to complete before next instruction. - barrier::isb(barrier::SY); - - Ok(()) - } -} diff --git a/12_exceptions_part1_groundwork/src/_arch/aarch64/time.rs b/12_exceptions_part1_groundwork/src/_arch/aarch64/time.rs deleted file mode 100644 index af98ddd01..000000000 --- a/12_exceptions_part1_groundwork/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) - } - - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; - - Duration::from_nanos(current_count / frq) - } - - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } - - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get() as u64; - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; - } - - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); - - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); - - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} - - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); - } -} diff --git a/12_exceptions_part1_groundwork/src/bsp.rs b/12_exceptions_part1_groundwork/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/12_exceptions_part1_groundwork/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/12_exceptions_part1_groundwork/src/bsp/device_driver.rs b/12_exceptions_part1_groundwork/src/bsp/device_driver.rs deleted file mode 100644 index ce7396f22..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/device_driver.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs b/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 59071d5d8..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index 15bd3b78b..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; - use core::time::Duration; - - // The Linux 2837 GPIO driver waits 1 µs between the steps. - const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index e39bc7cdb..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,323 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => _reserved3), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Read one character. - let mut ret = inner.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - inner.chars_read += 1; - - ret - }) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} diff --git a/12_exceptions_part1_groundwork/src/bsp/device_driver/common.rs b/12_exceptions_part1_groundwork/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/12_exceptions_part1_groundwork/src/bsp/raspberrypi.rs b/12_exceptions_part1_groundwork/src/bsp/raspberrypi.rs deleted file mode 100644 index 10888d37f..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs b/12_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs deleted file mode 100644 index d1b60dd82..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} diff --git a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs b/12_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs b/12_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index fe24dd71b..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/link.ld b/12_exceptions_part1_groundwork/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 90d096ffe..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,47 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - __ro_start = .; - .text : - { - *(.text._start) *(.text*) - } - - .exception_vectors : - { - *(.exception_vectors*) - } - - .rodata : - { - *(.rodata*) - } - . = ALIGN(65536); /* Fill up to 64 KiB */ - __ro_end = .; - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs b/12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 810acd8af..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -pub mod mmu; - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; - static __ro_start: UnsafeCell<()>; - static __ro_end: UnsafeCell<()>; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; - - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const END_INCLUSIVE: usize = 0x4000_FFFF; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const END_INCLUSIVE: usize = 0xFF84_FFFF; - } -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Start address of the Read-Only (RO) range. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_start() -> usize { - unsafe { __ro_start.get() as usize } -} - -/// Size of the Read-Only (RO) range of the kernel binary. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_end() -> usize { - unsafe { __ro_end.get() as usize } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs b/12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs deleted file mode 100644 index 5658ddb6d..000000000 --- a/12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs +++ /dev/null @@ -1,73 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management Unit. - -use super::map as memory_map; -use crate::memory::mmu::*; -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -const NUM_MEM_RANGES: usize = 2; - -/// The virtual memory layout. -/// -/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. -/// It is agnostic of the paging granularity that the architecture's MMU will use. -pub static LAYOUT: KernelVirtualLayout<{ NUM_MEM_RANGES }> = KernelVirtualLayout::new( - memory_map::END_INCLUSIVE, - [ - TranslationDescriptor { - name: "Kernel code and RO data", - virtual_range: ro_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadOnly, - execute_never: false, - }, - }, - TranslationDescriptor { - name: "Device MMIO", - virtual_range: mmio_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - }, - ], -); - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn ro_range_inclusive() -> RangeInclusive { - // Notice the subtraction to turn the exclusive end into an inclusive end. - #[allow(clippy::range_minus_one)] - RangeInclusive::new(super::ro_start(), super::ro_end() - 1) -} - -fn mmio_range_inclusive() -> RangeInclusive { - RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the address space size in bytes. -pub const fn addr_space_size() -> usize { - memory_map::END_INCLUSIVE + 1 -} - -/// Return a reference to the virtual memory layout. -pub fn virt_mem_layout() -> &'static KernelVirtualLayout<{ NUM_MEM_RANGES }> { - &LAYOUT -} diff --git a/12_exceptions_part1_groundwork/src/console.rs b/12_exceptions_part1_groundwork/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/12_exceptions_part1_groundwork/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/12_exceptions_part1_groundwork/src/cpu.rs b/12_exceptions_part1_groundwork/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/12_exceptions_part1_groundwork/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/12_exceptions_part1_groundwork/src/cpu/smp.rs b/12_exceptions_part1_groundwork/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/12_exceptions_part1_groundwork/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/12_exceptions_part1_groundwork/src/driver.rs b/12_exceptions_part1_groundwork/src/driver.rs deleted file mode 100644 index e2875b876..000000000 --- a/12_exceptions_part1_groundwork/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/12_exceptions_part1_groundwork/src/exception.rs b/12_exceptions_part1_groundwork/src/exception.rs deleted file mode 100644 index d2e621795..000000000 --- a/12_exceptions_part1_groundwork/src/exception.rs +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronous and asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/exception.rs"] -mod arch_exception; -pub use arch_exception::*; - -pub mod asynchronous; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Kernel privilege levels. -#[allow(missing_docs)] -#[derive(PartialEq)] -pub enum PrivilegeLevel { - User, - Kernel, - Hypervisor, - Unknown, -} diff --git a/12_exceptions_part1_groundwork/src/exception/asynchronous.rs b/12_exceptions_part1_groundwork/src/exception/asynchronous.rs deleted file mode 100644 index 3c75f90a2..000000000 --- a/12_exceptions_part1_groundwork/src/exception/asynchronous.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/exception/asynchronous.rs"] -mod arch_exception_async; -pub use arch_exception_async::*; diff --git a/12_exceptions_part1_groundwork/src/main.rs b/12_exceptions_part1_groundwork/src/main.rs deleted file mode 100644 index 6f59108aa..000000000 --- a/12_exceptions_part1_groundwork/src/main.rs +++ /dev/null @@ -1,228 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![allow(incomplete_features)] -#![feature(const_fn_fn_ptr_basics)] -#![feature(const_generics)] -#![feature(const_panic)] -#![feature(format_args_nl)] -#![feature(global_asm)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_main] -#![no_std] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - -mod bsp; -mod console; -mod cpu; -mod driver; -mod exception; -mod memory; -mod panic_wait; -mod print; -mod runtime_init; -mod synchronization; -mod time; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order: -/// - Virtual memory must be activated before the device drivers. -/// - Without it, any atomic operations, e.g. the yet-to-be-introduced spinlocks in the device -/// drivers (which currently employ NullLocks instead of spinlocks), will fail to work on -/// the RPi SoCs. -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - use memory::mmu::interface::MMU; - - exception::handling_init(); - - if let Err(string) = memory::mmu::mmu().init() { - panic!("MMU: {}", string); - } - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use console::interface::All; - use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; - - info!("Booting on: {}", bsp::board_name()); - - info!("MMU online. Special regions:"); - bsp::memory::mmu::virt_mem_layout().print_layout(); - - let (_, privilege_level) = exception::current_privilege_level(); - info!("Current privilege level: {}", privilege_level); - - info!("Exception handling state:"); - exception::asynchronous::print_state(); - - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() - ); - - info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } - - info!("Timer test, spinning for 1 second"); - time::time_manager().spin_for(Duration::from_secs(1)); - - // Cause an exception by accessing a virtual address for which no translation was set up. This - // code accesses the address 8 GiB, which is outside the mapped address space. - // - // For demo purposes, the exception handler will catch the faulting 8 GiB address and allow - // execution to continue. - info!(""); - info!("Trying to write to address 8 GiB..."); - let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; - unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; - - info!("************************************************"); - info!("Whoa! We recovered from a synchronous exception!"); - info!("************************************************"); - info!(""); - info!("Let's try again"); - - // Now use address 9 GiB. The exception handler won't forgive us this time. - info!("Trying to write to address 9 GiB..."); - big_addr = 9 * 1024 * 1024 * 1024; - unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; - - // Will never reach here in this tutorial. - info!("Echoing input now"); - loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); - } -} diff --git a/12_exceptions_part1_groundwork/src/memory.rs b/12_exceptions_part1_groundwork/src/memory.rs deleted file mode 100644 index 59236a120..000000000 --- a/12_exceptions_part1_groundwork/src/memory.rs +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -pub mod mmu; - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/12_exceptions_part1_groundwork/src/memory/mmu.rs b/12_exceptions_part1_groundwork/src/memory/mmu.rs deleted file mode 100644 index 25a18bf99..000000000 --- a/12_exceptions_part1_groundwork/src/memory/mmu.rs +++ /dev/null @@ -1,200 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Memory Management Unit. -//! -//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file -//! provides types for composing an architecture-agnostic description of the kernel 's virtual -//! memory layout. -//! -//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` -//! function. -//! -//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and -//! install respective translation tables. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/memory/mmu.rs"] -mod arch_mmu; -pub use arch_mmu::*; - -use core::{fmt, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Memory Management interfaces. -pub mod interface { - - /// MMU functions. - pub trait MMU { - /// Called by the kernel during early init. Supposed to take the translation tables from the - /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. - /// - /// # Safety - /// - /// - Changes the HW's global state. - unsafe fn init(&self) -> Result<(), &'static str>; - } -} - -/// Architecture agnostic translation types. -#[allow(missing_docs)] -#[allow(dead_code)] -#[derive(Copy, Clone)] -pub enum Translation { - Identity, - Offset(usize), -} - -/// Architecture agnostic memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum MemAttributes { - CacheableDRAM, - Device, -} - -/// Architecture agnostic access permissions. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum AccessPermissions { - ReadOnly, - ReadWrite, -} - -/// Collection of memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub struct AttributeFields { - pub mem_attributes: MemAttributes, - pub acc_perms: AccessPermissions, - pub execute_never: bool, -} - -/// Architecture agnostic descriptor for a memory range. -#[allow(missing_docs)] -pub struct TranslationDescriptor { - pub name: &'static str, - pub virtual_range: fn() -> RangeInclusive, - pub physical_range_translation: Translation, - pub attribute_fields: AttributeFields, -} - -/// Type for expressing the kernel's virtual memory layout. -pub struct KernelVirtualLayout { - /// The last (inclusive) address of the address space. - max_virt_addr_inclusive: usize, - - /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. - inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl Default for AttributeFields { - fn default() -> AttributeFields { - AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - } - } -} - -/// Human-readable output of a TranslationDescriptor. -impl fmt::Display for TranslationDescriptor { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Call the function to which self.range points, and dereference the result, which causes - // Rust to copy the value. - let start = *(self.virtual_range)().start(); - let end = *(self.virtual_range)().end(); - let size = end - start + 1; - - // log2(1024). - const KIB_RSHIFT: u32 = 10; - - // log2(1024 * 1024). - const MIB_RSHIFT: u32 = 20; - - let (size, unit) = if (size >> MIB_RSHIFT) > 0 { - (size >> MIB_RSHIFT, "MiB") - } else if (size >> KIB_RSHIFT) > 0 { - (size >> KIB_RSHIFT, "KiB") - } else { - (size, "Byte") - }; - - let attr = match self.attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => "C", - MemAttributes::Device => "Dev", - }; - - let acc_p = match self.attribute_fields.acc_perms { - AccessPermissions::ReadOnly => "RO", - AccessPermissions::ReadWrite => "RW", - }; - - let xn = if self.attribute_fields.execute_never { - "PXN" - } else { - "PX" - }; - - write!( - f, - " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", - start, end, size, unit, attr, acc_p, xn, self.name - ) - } -} - -impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { - /// Create a new instance. - pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { - Self { - max_virt_addr_inclusive: max, - inner: layout, - } - } - - /// For a virtual address, find and return the physical output address and corresponding - /// attributes. - /// - /// If the address is not found in `inner`, return an identity mapped default with normal - /// cacheable DRAM attributes. - pub fn virt_addr_properties( - &self, - virt_addr: usize, - ) -> Result<(usize, AttributeFields), &'static str> { - if virt_addr > self.max_virt_addr_inclusive { - return Err("Address out of range"); - } - - for i in self.inner.iter() { - if (i.virtual_range)().contains(&virt_addr) { - let output_addr = match i.physical_range_translation { - Translation::Identity => virt_addr, - Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), - }; - - return Ok((output_addr, i.attribute_fields)); - } - } - - Ok((virt_addr, AttributeFields::default())) - } - - /// Print the memory layout. - pub fn print_layout(&self) { - use crate::info; - - for i in self.inner.iter() { - info!("{}", i); - } - } -} diff --git a/12_exceptions_part1_groundwork/src/panic_wait.rs b/12_exceptions_part1_groundwork/src/panic_wait.rs deleted file mode 100644 index 1386e1e23..000000000 --- a/12_exceptions_part1_groundwork/src/panic_wait.rs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - cpu::wait_forever() -} diff --git a/12_exceptions_part1_groundwork/src/print.rs b/12_exceptions_part1_groundwork/src/print.rs deleted file mode 100644 index 8b6f3f988..000000000 --- a/12_exceptions_part1_groundwork/src/print.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} - -/// Prints an info, with a newline. -#[macro_export] -macro_rules! info { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} - -/// Prints a warning, with a newline. -#[macro_export] -macro_rules! warn { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} diff --git a/12_exceptions_part1_groundwork/src/runtime_init.rs b/12_exceptions_part1_groundwork/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/12_exceptions_part1_groundwork/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/12_exceptions_part1_groundwork/src/synchronization.rs b/12_exceptions_part1_groundwork/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/12_exceptions_part1_groundwork/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/12_exceptions_part1_groundwork/src/time.rs b/12_exceptions_part1_groundwork/src/time.rs deleted file mode 100644 index cd3ceec33..000000000 --- a/12_exceptions_part1_groundwork/src/time.rs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; -pub use arch_time::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); - } -} diff --git a/13_integrated_testing/.cargo/config.toml b/12_integrated_testing/.cargo/config.toml similarity index 100% rename from 13_integrated_testing/.cargo/config.toml rename to 12_integrated_testing/.cargo/config.toml diff --git a/12_integrated_testing/.vscode/settings.json b/12_integrated_testing/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/12_integrated_testing/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/12_integrated_testing/Cargo.lock b/12_integrated_testing/Cargo.lock new file mode 100644 index 000000000..8db3db876 --- /dev/null +++ b/12_integrated_testing/Cargo.lock @@ -0,0 +1,84 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.12.0" +dependencies = [ + "aarch64-cpu", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/12_integrated_testing/Cargo.toml b/12_integrated_testing/Cargo.toml new file mode 100644 index 000000000..6480a7276 --- /dev/null +++ b/12_integrated_testing/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +members = [ + "libraries/*", + "kernel" +] + +[profile.release] +lto = true diff --git a/12_integrated_testing/Makefile b/12_integrated_testing/Makefile new file mode 100644 index 000000000..4e2efeff3 --- /dev/null +++ b/12_integrated_testing/Makefile @@ -0,0 +1,334 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/12_integrated_testing/README.md b/12_integrated_testing/README.md new file mode 100644 index 000000000..ae68d2697 --- /dev/null +++ b/12_integrated_testing/README.md @@ -0,0 +1,923 @@ +# Tutorial 12 - Integrated Testing + +## tl;dr + +- We implement our own integrated test framework using `Rust`'s [custom_test_frameworks] feature by + enabling `Unit Tests` and `Integration Tests` using `QEMU`. +- It is also possible to have test automation for I/O with the kernel's `console` (provided over + `UART` in our case). That is, sending strings/characters to the console and expecting specific + answers in return. +- The already existing basic `boot test` remains unchanged. + + + +## Table of Contents + +- [Introduction](#introduction) +- [Challenges](#challenges) + * [Acknowledgements](#acknowledgements) +- [Folder Restructuring](#folder-restructuring) +- [Implementation](#implementation) + * [Test Organization](#test-organization) + * [Enabling `custom_test_frameworks` for Unit Tests](#enabling-custom_test_frameworks-for-unit-tests) + + [The Unit Test Runner](#the-unit-test-runner) + + [Calling the Test `main()` Function](#calling-the-test-main-function) + * [Quitting QEMU with user-defined Exit Codes](#quitting-qemu-with-user-defined-exit-codes) + + [Exiting Unit Tests](#exiting-unit-tests) + * [Controlling Test Kernel Execution](#controlling-test-kernel-execution) + + [Wrapping QEMU Test Execution](#wrapping-qemu-test-execution) + * [Writing Unit Tests](#writing-unit-tests) + * [Integration Tests](#integration-tests) + + [Test Harness](#test-harness) + + [No Test Harness](#no-test-harness) + + [Overriding Panic Behavior](#overriding-panic-behavior) + * [Console Tests](#console-tests) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +Through the course of the previous tutorials, we silently started to adopt a kind of anti-pattern: +Using the kernel's main function to not only boot the target, but also test or showcase +functionality. For example: + - Stalling execution during boot to test the kernel's timekeeping code by spinning for 1 second. + - Willingly causing exceptions to see the exception handler running. + +The feature set of the kernel is now rich enough so that it makes sense to introduce proper +integrated testing modeled after Rust's [native testing framework]. This tutorial extends our single +existing kernel test with three new testing facilities: + - Classic `Unit Tests`. + - [Integration Tests] (self-contained tests stored in the `$CRATE/tests/` directory). + - `Console I/O Tests`. These are integration tests acting on external stimuli - aka `console` + input. Sending strings/characters to the console and expecting specific answers in return. + +[native testing framework]: https://doc.rust-lang.org/book/ch11-00-testing.html + +## Challenges + +Testing Rust `#![no_std]` code like our kernel is, at the point of writing this tutorial, not an +easy endeavor. The short version is: We cannot use Rust's [native testing framework] straight away. +Utilizing the `#[test]` attribute macro and running `cargo test` would throw compilation errors, +because there are dependencies on the standard library. + +[native testing framework]: https://doc.rust-lang.org/book/ch11-00-testing.html + +We have to fall back to Rust's unstable [custom_test_frameworks] feature. It relieves us from +dependencies on the standard library, but comes at the cost of having a reduced feature set. Instead +of annotating functions with `#[test]`, the `#[test_case]` attribute must be used. Additionally, we +need to write a `test_runner` function, which is supposed to execute all the functions annotated +with `#[test_case]`. This is barely enough to get `Unit Tests` running, though. There will be some +more challenges that need be solved for getting `Integration Tests` running as well. + +Please note that for automation purposes, all testing will be done in `QEMU` and not on real +hardware. + +[custom_test_frameworks]: https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html +[Integration Tests]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests + +### Acknowledgements + +On this occasion, kudos to [@phil-opp] for his x86-based [testing] article. It helped a lot in +putting together this tutorial. Please go ahead and read it for a different perspective and +additional insights. + +[testing]: https://os.phil-opp.com/testing + +## Folder Restructuring + +For reasons explained later, in this tutorial, we need to add two support crates next to our main +kernel crate. To keep everything organized in separate directories, we are switching to what `cargo` +calls a [virtual manifest]. The kernel crate moves to `$ROOT/kernel`, and the support crates will go +into `$ROOT/libraries/`. The `Cargo.toml` in the `$ROOT` folder desribes this layout: + +```toml +[workspace] + +members = [ + "libraries/*", + "kernel" +] +``` + +[virtual manifest]: https://doc.rust-lang.org/cargo/reference/workspaces.html#virtual-manifest + +## Implementation + +We introduce two new `Makefile` targets: + +```console +$ make test_unit +$ make test_integration +``` + +In essence, the `make test_*` targets will execute `cargo test` instead of `cargo rustc`. The +details will be explained in due course. The rest of the tutorial will explain as chronologically as +possible what happens when `make test_*` aka `cargo test` runs. + +Please note that the new targets are added to the existing `make test` target, so this is now your +one-stop target to execute all possible tests for the kernel: + +```Makefile +test: test_boot test_unit test_integration +``` + +### Test Organization + +Until now, our kernel crate was a so-called `binary crate`. As [explained in the official Rust +book], this crate type disallows having `integration tests`. Quoting the book: + +[explained in the official Rust book]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests-for-binary-crates + +> If our project is a binary crate that only contains a _src/main.rs_ file and doesn’t have a +> _src/lib.rs_ file, we can’t create integration tests in the _tests_ directory and bring functions +> defined in the _src/main.rs_ file into scope with a `use` statement. Only library crates expose +> functions that other crates can use; binary crates are meant to be run on their own. + +> This is one of the reasons Rust projects that provide a binary have a straightforward +> _src/main.rs_ file that calls logic that lives in the _src/lib.rs_ file. Using that structure, +> integration tests _can_ test the library crate with `use` to make the important functionality +> available. If the important functionality works, the small amount of code in the _src/main.rs_ +> file will work as well, and that small amount of code doesn’t need to be tested. + +So let's do that first: We add a `lib.rs` to our crate that aggregates and exports the lion's share +of the kernel code. The `main.rs` file is stripped down to the minimum. It only keeps the +`kernel_init() -> !` and `kernel_main() -> !` functions, everything else is brought into scope with +`use` statements. + +Since it is not possible to use `kernel` as the name for both the library and the binary part of the +crate, new entries in `$ROOT/kernel/Cargo.toml` are needed to differentiate the names. What's more, +`cargo test` would try to compile and run `unit tests` for both. In our case, it will be sufficient +to have all the unit test code in `lib.rs`, so test generation for `main.rs` can be disabled in +`Cargo.toml` as well through the `test` flag: + +```toml +[lib] +name = "libkernel" +test = true + +[[bin]] +name = "kernel" +test = false +``` + +### Enabling `custom_test_frameworks` for Unit Tests + +In `lib.rs`, we add the following headers to get started with `custom_test_frameworks`: + +```rust +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] +``` + +Since this is a library now, we do not keep the `#![no_main]` inner attribute that `main.rs` has, +because a library has no `main()` entry function, so the attribute does not apply. When compiling +for testing, though, it is still needed. The reason is that `cargo test` basically turns `lib.rs` +into a binary again by inserting a generated `main()` function (which is then calling a function +that runs all the unit tests, but more about that in a second...). + +However, since our kernel code [overrides the compiler-inserted `main` shim] by way of using +`#![no_main]`, we need the same when `cargo test` is producing its test kernel binary. After all, +what we want is a minimal kernel that boots on the target and runs its own unit tests. Therefore, we +conditionally set this attribute (`#![cfg_attr(test, no_main)]`) when the `test` flag is set, which +it is when `cargo test` runs. + +[overrides the compiler-inserted `main` shim]: https://doc.rust-lang.org/unstable-book/language-features/lang-items.html?highlight=no_main#writing-an-executable-without-stdlib + +#### The Unit Test Runner + +The `#![test_runner(crate::test_runner)]` attribute declares the path of the test runner function +that we are supposed to provide. This is the one that will be called by the `cargo test` generated +`main()` function. Here is the implementation in `lib.rs`: + +```rust +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} +``` + +The function signature shows that `test_runner` takes one argument: A slice of +`test_types::UnitTest` references. This type definition lives in an external crate stored at +`$ROOT/libraries/test_types`. It is external because the type is also needed for a self-made +[procedural macro] that we'll use to write unit tests, and procedural macros _have_ to live in their +own crate. So to avoid a circular dependency between kernel and proc-macro, this split was needed. +Anyways, here is the type definition: + +[procedural macro]: https://doc.rust-lang.org/reference/procedural-macros.html + +```rust +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} +``` + +A `UnitTest` provides a name and a classic function pointer to the unit test function. The +`test_runner` just iterates over the slice, prints the respective test's name and calls the test +function. + +The convetion is that as long as the test function does not `panic!`, the test was successful. + +#### Calling the Test `main()` Function + +The last of the attributes we added is `#![reexport_test_harness_main = "test_main"]`. Remember that +our kernel uses the `no_main` attribute, and that we also set it for the test compilation. We did +that because we wrote our own `_start()` function, which kicks off the following call chain during +kernel boot: + +| | Function | File | +| - | - | - | +| 1. | `_start()` | The library's `boot.s` | +| 2. | (some more aarch64 code) | The library's `boot.rs` | +| 3. | `kernel_init()` | `main.rs` | +| 4. | `kernel_main()` | `main.rs` | + +A function named `main` is never called. Hence, the `main()` function generated by `cargo test` +would be silently dropped, and therefore the tests would never be executed. As you can see, the +first function getting called in our carved-out `main.rs` is `kernel_init()`. So in order to get the +tests to execute, we add a test-environment version of `kernel_init()` to `lib.rs` as well +(conditional compilation ensures it is only present when the test flag is set), and call the `cargo +test` generated `main()` function from there. + +This is where `#![reexport_test_harness_main = "test_main"]` finally comes into picture. It declares +the name of the generated main function so that we can manually call it. Here is the final +implementation in `lib.rs`: + +```rust +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} +``` + +Note the call to `bsp::driver::qemu_bring_up_console()`. Since we are running all our tests inside +`QEMU`, we need to ensure that whatever peripheral implements the kernel's `console` interface is +initialized, so that we can print from our tests. If you recall [tutorial 03], bringing up +peripherals in `QEMU` might not need the full initialization as is needed on real hardware (setting +clocks, config registers, etc...) due to the abstractions in `QEMU`'s emulation code. So this is an +opportunity to cut down on setup code. + +[tutorial 03]: ../03_hacky_hello_world + +As a matter of fact, for the `Raspberrys`, nothing needs to be done, so the function is empy. But +this might be different for other hardware emulated by `QEMU`, so it makes sense to introduce the +function now to make it easier in case new `BSPs` are added to the kernel in the future. + +Next, the reexported `test_main()` is called, which will call our `test_runner()` which finally +prints the unit test names and executes them. + +### Quitting QEMU with user-defined Exit Codes + +Let's recap where we are right now: + +We've enabled `custom_test_frameworks` in `lib.rs` to a point where, when using a `make test_unit` +target, the code gets compiled to a test kernel binary that eventually executes all the +(yet-to-be-defined) `UnitTest` instances by executing all the way from `_start()` to our +`test_runner()` function. + +Through mechanisms that are explained later, `cargo` will now instantiate a `QEMU` process that +exectues this test kernel. The question now is: How is test success/failure communicated to `cargo`? +Answer: `cargo` inspects `QEMU`'s [exit status]: + + - `0` translates to testing was successful. + - `non-0` means failure. + +Hence, we need a clever trick now so that our Rust kernel code can get `QEMU` to exit itself with an +exit status that the kernel code supplies. In [@phil-opp]'s testing article, you [learned how to do +this] for `x86 QEMU` systems by using a special `ISA` debug-exit device. Unfortunately, we can't +have that one for our `aarch64` system because it is not compatible. + +In our case, we can leverage the ARM [semihosting] emulation of `QEMU` and do a `SYS_EXIT` +semihosting call with an additional parameter for the exit code. I've written a separate crate, +[qemu-exit], to do this. So let us import it and utilize it in `_arch/aarch64/cpu.rs` to provide the +following exit calls for the kernel: + +```rust +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} +``` + +[Click here] in case you are interested in the implementation. Note that for the functions to work, +the `-semihosting` flag must be added to the `QEMU` invocation. + +You might have also noted the `#[cfg(feature = "test_build")]`. In the `Makefile`, we ensure that +this feature is only enabled when `cargo test` runs. This way, it is ensured that testing-specific +code is conditionally compiled only for testing. + +[exit status]: https://en.wikipedia.org/wiki/Exit_status +[@phil-opp]: https://github.com/phil-opp +[learned how to do this]: https://os.phil-opp.com/testing/#exiting-qemu +[semihosting]: https://static.docs.arm.com/100863/0200/semihosting.pdf +[qemu-exit]: https://github.com/andre-richter/qemu-exit +[Click here]: https://github.com/andre-richter/qemu-exit/blob/master/src/aarch64.rs + +#### Exiting Unit Tests + +Unit test failure shall be triggered by the `panic!` macro, either directly or by way of using +`assert!` macros. Until now, our `panic!` implementation finally called `cpu::wait_forever()` to +safely park the panicked CPU core in a busy loop. This can't be used for the unit tests, because +`cargo` would wait forever for `QEMU` to exit and stall the whole test run. Again, conditional +compilation is used to differentiate between a release and testing version of how a `panic!` +concludes: + +```rust +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} +``` + +In case _none_ of the unit tests panicked, `lib.rs`'s `kernel_init()` calls +`cpu::qemu_exit_success()` to successfully conclude the unit test run. + +### Controlling Test Kernel Execution + +Now is a good time to catch up on how the test kernel binary is actually being executed. Normally, +`cargo test` would try to execute the compiled binary as a normal child process. This would fail +horribly because we build a kernel, and not a userspace process. Also, chances are high that you sit +in front of an `x86` machine, whereas the RPi kernel is `AArch64`. + +Therefore, we need to install some hooks that make sure the test kernel gets executed inside `QEMU`, +quite like it is done for the existing `make qemu` target that is in place since `tutorial 1`. The +first step is to add a new file to the project, `.cargo/config.toml`: + +```toml +[target.'cfg(target_os = "none")'] +runner = "target/kernel_test_runner.sh" +``` + +Instead of executing a compilation result directly, the `runner` flag will instruct `cargo` to +delegate the execution. Using the setting depicted above, `target/kernel_test_runner.sh` will be +executed and given the full path to the compiled test kernel as the first command line argument. + +The file `kernel_test_runner.sh` does not exist by default. We generate it on demand when one of the +`make test_*` targets is called: + +```Makefile +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER + #!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib +``` + +It first does the standard `objcopy` step to strip the `ELF` down to a raw binary. Just like in all +the other Makefile targets. Next, the script generates a relative path from the absolute path +provided to it by `cargo`, and finally compiles a `docker` command to execute the test kernel. For +reference, here it is fully resolved for an `RPi3 BSP`: + +```bash +docker run -t --rm -v /opt/rust-raspberrypi-OS-tutorials/12_integrated_testing:/work/tutorial -w /work/tutorial -v /opt/rust-raspberrypi-OS-tutorials/12_integrated_testing/../common:/work/common rustembedded/osdev-utils:2021.12 ruby ../common/tests/dispatch.rb qemu-system-aarch64 -M raspi3 -serial stdio -display none -semihosting -kernel $TEST_BINARY +``` + +This command is quite similar to the one used in the `make test_boot` target that we have since +`tutorial 3`. However, we never bothered explaining it, so lets take a closer look this time. One of +the key ingredients is that we execute this script: `ruby ../common/tests/dispatch.rb`. + +#### Wrapping QEMU Test Execution + +`dispatch.rb` is a [Ruby] script which first determines what kind of test is due by inspecting the +`QEMU`-command that was given to it. In case of `unit tests`, we are only interested if they all +executed successfully, which can be checked by inspecting `QEMU`'s exit code. So the script takes +the provided qemu command it got from `ARGV`, and creates and runs an instance of `ExitCodeTest`: + +```ruby +qemu_cmd = ARGV.join(' ') +binary = ARGV.last +test_name = binary.gsub(%r{.*deps/}, '').split('-')[0] + +# Check if virtual manifest (tutorial 12 or later) or not +path_prefix = File.exist?('kernel/Cargo.toml') ? 'kernel/' : '' + +case test_name +when 'kernel8.img' + load "#{path_prefix}tests/boot_test_string.rb" # provides 'EXPECTED_PRINT' + BootTest.new(qemu_cmd, EXPECTED_PRINT).run # Doesn't return + +when 'libkernel' + ExitCodeTest.new(qemu_cmd, 'Kernel library unit tests').run # Doesn't return +``` + +The easy case is `QEMU` exiting by itself by means of `aarch64::exit_success()` or +`aarch64::exit_failure()`. But the script can also catch the case of a test that gets stuck, e.g. in +an unintentional busy loop or a crash. If `ExitCodeTest` does not observe any output of the test +kernel for `MAX_WAIT_SECS`, it cancels the execution and marks the test as failed. Test success or +failure is finally reported back to `cargo`. + +Here is the essential part happening in `class ExitCodeTest` (If `QEMU` exits itself, an `EOFError` +is thrown): + +```ruby +def run_concrete_test + Timeout.timeout(MAX_WAIT_SECS) do + @test_output << @qemu_serial.read_nonblock(1024) while @qemu_serial.wait_readable + end +rescue EOFError + @qemu_serial.close + @test_error = $CHILD_STATUS.to_i.zero? ? false : 'QEMU exit status != 0' +rescue Timeout::Error + @test_error = 'Timed out waiting for test' +rescue StandardError => e + @test_error = e.inspect +end +``` + +Please note that `dispatch.rb` and all its dependencies live in the shared folder +`../common/tests/`. + +[Ruby]: https://www.ruby-lang.org/ + +### Writing Unit Tests + +Alright, that's a wrap for the whole chain from `make test_unit` all the way to reporting the test +exit status back to `cargo test`. It is a lot to digest already, but we haven't even learned to +write `Unit Tests` yet. + +In essence, it is almost like in `std` environments, with the difference that `#[test]` can't be +used, because it is part of the standard library. The `no_std` replacement attribute provided by +`custom_test_frameworks` is `#[test_case]`. You can put `#[test_case]` before functions, constants +or statics (you have to decide for one and stick with it). Each attributed item is added to the +"list" that is then passed to the `test_runner` function. + +As you learned earlier, we decided that our tests shall be instances of `test_types::UnitTest`. Here +is the type definition again: + +```rust +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} +``` + +So what we could do now is write something like: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test_case] + const TEST1: test_types::UnitTest = test_types::UnitTest { + name: "test_runner_executes_in_kernel_mode", + test_func: || { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + }, + }; +} +``` + +Since this is a bit boiler-platy with the const and name definition, let's write a [procedural +macro] named `#[kernel_test]` to simplify this. It should work this way: + + 1. Must be put before functions that take no arguments and return nothing. + 1. Automatically constructs a `const UnitTest` from attributed functions like shown above by: + 1. Converting the function name to the `name` member of the `UnitTest` struct. + 1. Populating the `test_func` member with a closure that executes the body of the attributed + function. + +For the sake of brevity, we're not going to discuss the macro implementation. [The source is in the +test-macros crate] if you're interested in it. Using the macro, the example shown before now boils +down to this (this is now an actual example from [exception.rs]: + +[procedural macro]: https://doc.rust-lang.org/reference/procedural-macros.html +[The source is in the test-macros crate]: test-macros/src/lib.rs +[exception.rs]: src/exception.rs + +```rust +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} +``` + +Note that since proc macros need to live in their own crates, we need to create a new one at +`$ROOT/libraries/test-macros` and save it there. + +Aaaaaand that's how you write unit tests. We're finished with that part for good now :raised_hands:. + +### Integration Tests + +We are still not done with the tutorial, though :scream:. + +Integration tests need some special attention here and there too. As you already learned, they live +in `$CRATE/tests/`. Each `.rs` file in there gets compiled into its own test kernel binary and +executed separately by `cargo test`. The code in the integration tests includes the library part of +our kernel (`libkernel`) through `use` statements. + +Also note that the entry point for each `integration test` must be the `kernel_init()` function +again, just like in the `unit test` case. + +#### Test Harness + +By default, `cargo test` will pull in the test harness (that's the official name for the generated +`main()` function) into integration tests as well. This gives you a further means of partitioning +your test code into individual chunks. For example, take a look at `tests/01_timer_sanity.rs`: + +```rust +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} +``` + +Note how the `test_runner` from `libkernel` is pulled in through +`#![test_runner(libkernel::test_runner)]`. + +#### No Test Harness + +For some tests, however, it is not needed to have the harness, because there is no need or +possibility to partition the test into individual pieces. In this case, all the test code can live +in `kernel_init()`, and harness generation can be turned off through `$ROOT/kernel/Cargo.toml`. This +tutorial introduces two tests that don't need a harness. Here is how harness generation is turned +off for them: + +```toml +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false +``` + +#### Overriding Panic Behavior + +Did you notice the `#[linkage = "weak"]` attribute some chapters earlier at the `_panic_exit()` +function? This marks the function in `lib.rs` as a [weak symbol]. Let's look at it again: + +```rust +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} +``` + +[weak symbol]: https://en.wikipedia.org/wiki/Weak_symbol + +This enables integration tests in `$CRATE/tests/` to override this function according to their +needs. This is useful, because depending on the kind of test, a `panic!` could mean success or +failure. For example, `tests/02_exception_sync_page_fault.rs` is intentionally causing a page fault, +so the wanted outcome is a `panic!`. Here is the whole test (minus some inline comments): + +```rust +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + info!("MMU: {}", string); + cpu::qemu_exit_failure() + } + + info!("Writing beyond mapped area to address 9 GiB..."); + let big_addr: u64 = 9 * 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} +``` + +The `_panic_exit()` version that makes `QEMU` return `0` (indicating test success) is pulled in by +`mod panic_exit_success;`, and it will take precedence over the `weak` version from `lib.rs`. + +### Console Tests + +As the kernel or OS grows, it will be more and more interesting to test user/kernel interaction +through the serial console. That is, sending strings/characters to the console and expecting +specific answers in return. The `dispatch.rb` wrapper script provides infrastructure to recognize +and dispatch console I/O tests with little overhead. It basically works like this: + + 1. For each integration test, check if a companion file to the `.rs` test file exists. + - A companion file has the same name, but ends in `.rb`. + - The companion file contains one or more console I/O subtests. + 1. If it exists, load the file to dynamically import the console subtests. + 1. Create a `ConsoleIOTest` instance and run it. + - This first spawns `QEMU` and attaches to `QEMU`'s serial console emulation. + - Then it runs all console subtests on it. + +Here is an excerpt from `00_console_sanity.rb` showing a subtest that does a handshake with the +kernel over the console: + +```ruby +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end +``` + +The subtest first sends `"ABC"` over the console to the kernel, and then expects to receive +`"OK1234"` back. On the kernel side, it looks like this in `00_console_sanity.rs`: + +```rust +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); +``` + +## Test it + +Believe it or not, that is all. There are four ways you can run tests now: + + 1. `make test` will run all tests back-to-back. That is, the ever existing `boot test` first, then + `unit tests`, then `integration tests`. + 1. `make test_unit` will run `libkernel`'s unit tests. + 1. `make test_integration` will run all integration tests back-to-back. + 1. `TEST=TEST_NAME make test_integration` will run a specficic integration test. + - For example, `TEST=01_timer_sanity make test_integration` + +```console +$ make test +[...] + + Running unittests (target/aarch64-unknown-none-softfloat/release/deps/libkernel-142a8d94bc9c615a) + ------------------------------------------------------------------- + 🦀 Running 6 tests + ------------------------------------------------------------------- + + 1. virt_mem_layout_sections_are_64KiB_aligned................[ok] + 2. virt_mem_layout_has_no_overlaps...........................[ok] + 3. test_runner_executes_in_kernel_mode.......................[ok] + 4. kernel_tables_in_bss......................................[ok] + 5. size_of_tabledescriptor_equals_64_bit.....................[ok] + 6. size_of_pagedescriptor_equals_64_bit......................[ok] + + ------------------------------------------------------------------- + ✅ Success: Kernel library unit tests + ------------------------------------------------------------------- + + + +Compiling integration test(s) - rpi3 + Finished release [optimized] target(s) in 0.00s + Running tests/00_console_sanity.rs (target/aarch64-unknown-none-softfloat/release/deps/00_console_sanity-c06130838f14dbff) + ------------------------------------------------------------------- + 🦀 Running 3 console I/O tests + ------------------------------------------------------------------- + + 1. Transmit and Receive handshake............................[ok] + 2. Transmit statistics.......................................[ok] + 3. Receive statistics........................................[ok] + + Console log: + ABCOK123463 + + ------------------------------------------------------------------- + ✅ Success: 00_console_sanity.rs + ------------------------------------------------------------------- + + + Running tests/01_timer_sanity.rs (target/aarch64-unknown-none-softfloat/release/deps/01_timer_sanity-62a954d22239d1a3) + ------------------------------------------------------------------- + 🦀 Running 3 tests + ------------------------------------------------------------------- + + 1. timer_is_counting.........................................[ok] + 2. timer_resolution_is_sufficient............................[ok] + 3. spin_accuracy_check_1_second..............................[ok] + + ------------------------------------------------------------------- + ✅ Success: 01_timer_sanity.rs + ------------------------------------------------------------------- + + + Running tests/02_exception_sync_page_fault.rs (target/aarch64-unknown-none-softfloat/release/deps/02_exception_sync_page_fault-2d8ec603ef1c4d8e) + ------------------------------------------------------------------- + 🦀 Testing synchronous exception handling by causing a page fault + ------------------------------------------------------------------- + + [ 0.132792] Writing beyond mapped area to address 9 GiB... + [ 0.134563] Kernel panic! + + Panic location: + File 'src/_arch/aarch64/exception.rs', line 58, column 5 + + CPU Exception! + + ESR_EL1: 0x96000004 + Exception Class (EC) : 0x25 - Data Abort, current EL + [...] + + ------------------------------------------------------------------- + ✅ Success: 02_exception_sync_page_fault.rs + ------------------------------------------------------------------- + + + Running tests/03_exception_restore_sanity.rs (target/aarch64-unknown-none-softfloat/release/deps/03_exception_restore_sanity-a56e14285bb26e0e) + ------------------------------------------------------------------- + 🦀 Running 1 console I/O tests + ------------------------------------------------------------------- + + 1. Exception restore.........................................[ok] + + Console log: + Testing exception restore + [ 0.130757] Making a dummy system call + [ 0.132592] Back from system call! + + ------------------------------------------------------------------- + ✅ Success: 03_exception_restore_sanity.rs + ------------------------------------------------------------------- + +``` + +## Diff to previous + +The diff in this tutorial is skipped, because due to the changes in top-level folder structure, it +becomes unreadable. This might be fixed in the future. For now, consider using a diff tool like +`meld` to diff between the previous and the `kernel` folder of this tutorial to see the lion's share +of changes: + +```console +meld 11_exceptions_part1_groundwork 12_integrated_testing/kernel +``` diff --git a/12_integrated_testing/kernel/Cargo.toml b/12_integrated_testing/kernel/Cargo.toml new file mode 100644 index 000000000..97dd972e0 --- /dev/null +++ b/12_integrated_testing/kernel/Cargo.toml @@ -0,0 +1,57 @@ +[package] +name = "mingo" +version = "0.12.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##-------------------------------------------------------------------------------------------------- +## Testing +##-------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false diff --git a/12_integrated_testing/kernel/build.rs b/12_integrated_testing/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/12_integrated_testing/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/cpu.rs b/12_integrated_testing/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.rs b/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..c80f3ebbc --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(crate::kernel_init as *const () as u64); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.s b/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..f6df21236 --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. x0 holds the function argument provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/exception.rs b/12_integrated_testing/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..4df4adab4 --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,311 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!(include_str!("exception.s")); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/exception.s b/12_integrated_testing/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..91805ee7c --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 17 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs b/12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..65fcad25d --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu.rs b/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..99ecaa2bf --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// # Safety +/// +/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". +static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + fn configure_translation_control(&self) { + let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI0::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG0::KiB_64 + + TCR_EL1::SH0::Inner + + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD0::EnableTTBR0Walks + + TCR_EL1::A1::TTBR0 + + TCR_EL1::T0SZ.val(t0sz) + + TCR_EL1::EPD1::DisableTTBR1Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Populate translation tables. + KERNEL_TABLES + .populate_tt_entries() + .map_err(MMUEnableError::Other)?; + + // Set the "Translation Table Base Register". + TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use core::{cell::UnsafeCell, ops::Range}; + use test_macros::kernel_test; + + /// Check if KERNEL_TABLES is in .bss. + #[kernel_test] + fn kernel_tables_in_bss() { + extern "Rust" { + static __bss_start: UnsafeCell; + static __bss_end_exclusive: UnsafeCell; + } + + let bss_range = unsafe { + Range { + start: __bss_start.get(), + end: __bss_end_exclusive.get(), + } + }; + let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; + + assert!(bss_range.contains(&kernel_tables_addr)); + } +} diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..5e45a5fdf --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,320 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, memory, + memory::mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn phys_start_addr_u64(&self) -> u64; + fn phys_start_addr_usize(&self) -> usize; +} + +const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], +} + +/// A translation table type for the kernel space. +pub type KernelTranslationTable = FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +// The binary is still identity mapped, so we don't need to convert here. +impl StartAddr for [T; N] { + fn phys_start_addr_u64(&self) -> u64 { + self as *const T as u64 + } + + fn phys_start_addr_usize(&self) -> usize { + self as *const _ as usize + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl FixedSizeTranslationTable { + /// Create an instance. + pub const fn new() -> Self { + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + } + } + + /// Iterates over all static translation table entries and fills them at once. + /// + /// # Safety + /// + /// - Modifies a `static mut`. Ensure it only happens from here. + pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { + for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { + *l2_entry = + TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); + + for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { + let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); + + let (phys_output_addr, attribute_fields) = + bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; + + *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); + } + } + + Ok(()) + } + + /// The translation table's base address to be used for programming the MMU. + pub fn phys_base_address(&self) -> u64 { + self.lvl2.phys_start_addr_u64() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/12_integrated_testing/kernel/src/_arch/aarch64/time.rs b/12_integrated_testing/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/12_integrated_testing/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/12_integrated_testing/kernel/src/bsp.rs b/12_integrated_testing/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/12_integrated_testing/kernel/src/bsp/device_driver.rs b/12_integrated_testing/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..64049a4cf --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs b/12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..1c343d1d7 --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..8e57dfedb --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..d92612ea8 --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff --git a/12_integrated_testing/kernel/src/bsp/device_driver/common.rs b/12_integrated_testing/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..dfe7d8ef3 --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff --git a/12_integrated_testing/kernel/src/bsp/raspberrypi.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..3ea864dc7 --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/12_integrated_testing/kernel/src/bsp/raspberrypi/cpu.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/12_integrated_testing/kernel/src/bsp/raspberrypi/driver.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..7ecb48c8d --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + console::register_console(&PL011_UART); +} diff --git a/12_integrated_testing/kernel/src/bsp/raspberrypi/kernel.ld b/12_integrated_testing/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..6d939889b --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..661476f4a --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | +//! | | +pub mod mmu; + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + /// The inclusive end address of the memory map. + /// + /// End address + 1 must be power of two. + /// + /// # Note + /// + /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for + /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. + /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. + /// + /// However, making this trade-off has the downside of making it possible for the CPU to assert a + /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on + /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. + pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0x4000_FFFF; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0xFF84_FFFF; + } +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_start() -> usize { + unsafe { __code_start.get() as usize } +} + +/// Exclusive end page address of the code segment. +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_end_exclusive() -> usize { + unsafe { __code_end_exclusive.get() as usize } +} diff --git a/12_integrated_testing/kernel/src/bsp/raspberrypi/memory/mmu.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..563c8ba9b --- /dev/null +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use super::map as memory_map; +use crate::memory::mmu::*; +use core::ops::RangeInclusive; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The kernel's address space defined by this BSP. +pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; + +const NUM_MEM_RANGES: usize = 2; + +/// The virtual memory layout. +/// +/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. +/// It is agnostic of the paging granularity that the architecture's MMU will use. +pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( + memory_map::END_INCLUSIVE, + [ + TranslationDescriptor { + name: "Kernel code and RO data", + virtual_range: code_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadOnly, + execute_never: false, + }, + }, + TranslationDescriptor { + name: "Device MMIO", + virtual_range: mmio_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + }, + ], +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn code_range_inclusive() -> RangeInclusive { + // Notice the subtraction to turn the exclusive end into an inclusive end. + #[allow(clippy::range_minus_one)] + RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) +} + +fn mmio_range_inclusive() -> RangeInclusive { + RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the virtual memory layout. +pub fn virt_mem_layout() -> &'static KernelVirtualLayout { + &LAYOUT +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check alignment of the kernel's virtual memory layout sections. + #[kernel_test] + fn virt_mem_layout_sections_are_64KiB_aligned() { + const SIXTYFOUR_KIB: usize = 65536; + + for i in LAYOUT.inner().iter() { + let start: usize = *(i.virtual_range)().start(); + let end: usize = *(i.virtual_range)().end() + 1; + + assert_eq!(start % SIXTYFOUR_KIB, 0); + assert_eq!(end % SIXTYFOUR_KIB, 0); + assert!(end >= start); + } + } + + /// Ensure the kernel's virtual memory layout is free of overlaps. + #[kernel_test] + fn virt_mem_layout_has_no_overlaps() { + let layout = virt_mem_layout().inner(); + + for (i, first) in layout.iter().enumerate() { + for second in layout.iter().skip(i + 1) { + let first_range = first.virtual_range; + let second_range = second.virtual_range; + + assert!(!first_range().contains(second_range().start())); + assert!(!first_range().contains(second_range().end())); + assert!(!second_range().contains(first_range().start())); + assert!(!second_range().contains(first_range().end())); + } + } + } +} diff --git a/12_integrated_testing/kernel/src/common.rs b/12_integrated_testing/kernel/src/common.rs new file mode 100644 index 000000000..782a5da15 --- /dev/null +++ b/12_integrated_testing/kernel/src/common.rs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/12_integrated_testing/kernel/src/console.rs b/12_integrated_testing/kernel/src/console.rs new file mode 100644 index 000000000..a83f86fe0 --- /dev/null +++ b/12_integrated_testing/kernel/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization::{self, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) +} diff --git a/12_integrated_testing/kernel/src/console/null_console.rs b/12_integrated_testing/kernel/src/console/null_console.rs new file mode 100644 index 000000000..cbb7ec7d8 --- /dev/null +++ b/12_integrated_testing/kernel/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/12_integrated_testing/kernel/src/cpu.rs b/12_integrated_testing/kernel/src/cpu.rs new file mode 100644 index 000000000..1f6b57f3d --- /dev/null +++ b/12_integrated_testing/kernel/src/cpu.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/12_integrated_testing/kernel/src/cpu/boot.rs b/12_integrated_testing/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/12_integrated_testing/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/12_integrated_testing/kernel/src/driver.rs b/12_integrated_testing/kernel/src/driver.rs new file mode 100644 index 000000000..050e7022f --- /dev/null +++ b/12_integrated_testing/kernel/src/driver.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + info, + synchronization::{interface::Mutex, NullLock}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/12_integrated_testing/kernel/src/exception.rs b/12_integrated_testing/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/12_integrated_testing/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/12_integrated_testing/kernel/src/exception/asynchronous.rs b/12_integrated_testing/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..fd059326e --- /dev/null +++ b/12_integrated_testing/kernel/src/exception/asynchronous.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::print_state; diff --git a/12_integrated_testing/kernel/src/lib.rs b/12_integrated_testing/kernel/src/lib.rs new file mode 100644 index 000000000..16e0b1d08 --- /dev/null +++ b/12_integrated_testing/kernel/src/lib.rs @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(int_roundings)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +mod panic_wait; +mod synchronization; + +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +#[cfg(not(test))] +extern "Rust" { + fn kernel_init() -> !; +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/12_integrated_testing/kernel/src/main.rs b/12_integrated_testing/kernel/src/main.rs new file mode 100644 index 000000000..9a8df1d7c --- /dev/null +++ b/12_integrated_testing/kernel/src/main.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +use libkernel::{bsp, console, driver, exception, info, memory, time}; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order: +/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, +/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ +/// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. +#[no_mangle] +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + exception::handling_init(); + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + panic!("MMU: {}", string); + } + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + use console::console; + + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online. Special regions:"); + bsp::memory::mmu::virt_mem_layout().print_layout(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Echoing input now"); + + // Discard any spurious received characters before going into echo mode. + console().clear_rx(); + loop { + let c = console().read_char(); + console().write_char(c); + } +} diff --git a/12_integrated_testing/kernel/src/memory.rs b/12_integrated_testing/kernel/src/memory.rs new file mode 100644 index 000000000..6dd8f186b --- /dev/null +++ b/12_integrated_testing/kernel/src/memory.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; diff --git a/12_integrated_testing/kernel/src/memory/mmu.rs b/12_integrated_testing/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..7c7fc3974 --- /dev/null +++ b/12_integrated_testing/kernel/src/memory/mmu.rs @@ -0,0 +1,257 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. +//! +//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file +//! provides types for composing an architecture-agnostic description of the kernel's virtual memory +//! layout. +//! +//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` +//! function. +//! +//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and +//! install respective translation tables. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod translation_table; + +use crate::common; +use core::{fmt, ops::RangeInclusive}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_mmu::mmu; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Called by the kernel during early init. Supposed to take the translation tables from the + /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Architecture agnostic translation types. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum Translation { + Identity, + Offset(usize), +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// Architecture agnostic descriptor for a memory range. +#[allow(missing_docs)] +pub struct TranslationDescriptor { + pub name: &'static str, + pub virtual_range: fn() -> RangeInclusive, + pub physical_range_translation: Translation, + pub attribute_fields: AttributeFields, +} + +/// Type for expressing the kernel's virtual memory layout. +pub struct KernelVirtualLayout { + /// The last (inclusive) address of the address space. + max_virt_addr_inclusive: usize, + + /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. + inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +impl Default for AttributeFields { + fn default() -> AttributeFields { + AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + } + } +} + +/// Human-readable output of a TranslationDescriptor. +impl fmt::Display for TranslationDescriptor { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Call the function to which self.range points, and dereference the result, which causes + // Rust to copy the value. + let start = *(self.virtual_range)().start(); + let end = *(self.virtual_range)().end(); + let size = end - start + 1; + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match self.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match self.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if self.attribute_fields.execute_never { + "PXN" + } else { + "PX" + }; + + write!( + f, + " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", + start, end, size, unit, attr, acc_p, xn, self.name + ) + } +} + +impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { + /// Create a new instance. + pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { + Self { + max_virt_addr_inclusive: max, + inner: layout, + } + } + + /// For a virtual address, find and return the physical output address and corresponding + /// attributes. + /// + /// If the address is not found in `inner`, return an identity mapped default with normal + /// cacheable DRAM attributes. + pub fn virt_addr_properties( + &self, + virt_addr: usize, + ) -> Result<(usize, AttributeFields), &'static str> { + if virt_addr > self.max_virt_addr_inclusive { + return Err("Address out of range"); + } + + for i in self.inner.iter() { + if (i.virtual_range)().contains(&virt_addr) { + let output_addr = match i.physical_range_translation { + Translation::Identity => virt_addr, + Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), + }; + + return Ok((output_addr, i.attribute_fields)); + } + } + + Ok((virt_addr, AttributeFields::default())) + } + + /// Print the memory layout. + pub fn print_layout(&self) { + use crate::info; + + for i in self.inner.iter() { + info!("{}", i); + } + } + + #[cfg(test)] + pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { + &self.inner + } +} diff --git a/12_integrated_testing/kernel/src/memory/mmu/translation_table.rs b/12_integrated_testing/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..1a2581aac --- /dev/null +++ b/12_integrated_testing/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_translation_table::KernelTranslationTable; diff --git a/12_integrated_testing/kernel/src/panic_wait.rs b/12_integrated_testing/kernel/src/panic_wait.rs new file mode 100644 index 000000000..a896ad5e3 --- /dev/null +++ b/12_integrated_testing/kernel/src/panic_wait.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + _panic_exit() +} diff --git a/12_integrated_testing/kernel/src/print.rs b/12_integrated_testing/kernel/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/12_integrated_testing/kernel/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/12_integrated_testing/kernel/src/synchronization.rs b/12_integrated_testing/kernel/src/synchronization.rs new file mode 100644 index 000000000..94c83de1c --- /dev/null +++ b/12_integrated_testing/kernel/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} diff --git a/12_integrated_testing/kernel/src/time.rs b/12_integrated_testing/kernel/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/12_integrated_testing/kernel/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/12_integrated_testing/kernel/tests/00_console_sanity.rb b/12_integrated_testing/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/12_integrated_testing/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/12_integrated_testing/kernel/tests/00_console_sanity.rs b/12_integrated_testing/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..982c61708 --- /dev/null +++ b/12_integrated_testing/kernel/tests/00_console_sanity.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/12_integrated_testing/kernel/tests/01_timer_sanity.rs b/12_integrated_testing/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..3b065f13f --- /dev/null +++ b/12_integrated_testing/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/12_integrated_testing/kernel/tests/02_exception_sync_page_fault.rs b/12_integrated_testing/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..bf5b7d711 --- /dev/null +++ b/12_integrated_testing/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + info!("MMU: {}", string); + cpu::qemu_exit_failure() + } + + info!("Writing beyond mapped area to address 9 GiB..."); + let big_addr: u64 = 9 * 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rb b/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rs b/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..e22f49775 --- /dev/null +++ b/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + info!("MMU: {}", string); + cpu::qemu_exit_failure() + } + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/12_integrated_testing/kernel/tests/boot_test_string.rb b/12_integrated_testing/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/12_integrated_testing/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/12_integrated_testing/kernel/tests/panic_exit_success/mod.rs b/12_integrated_testing/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/12_integrated_testing/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/12_integrated_testing/kernel/tests/panic_wait_forever/mod.rs b/12_integrated_testing/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/12_integrated_testing/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/12_integrated_testing/libraries/test-macros/Cargo.toml b/12_integrated_testing/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/12_integrated_testing/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/12_integrated_testing/libraries/test-macros/src/lib.rs b/12_integrated_testing/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/12_integrated_testing/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/12_integrated_testing/libraries/test-types/Cargo.toml b/12_integrated_testing/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/12_integrated_testing/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/12_integrated_testing/libraries/test-types/src/lib.rs b/12_integrated_testing/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/12_integrated_testing/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/14_exceptions_part2_peripheral_IRQs/.cargo/config.toml b/13_exceptions_part2_peripheral_IRQs/.cargo/config.toml similarity index 100% rename from 14_exceptions_part2_peripheral_IRQs/.cargo/config.toml rename to 13_exceptions_part2_peripheral_IRQs/.cargo/config.toml diff --git a/13_exceptions_part2_peripheral_IRQs/.vscode/settings.json b/13_exceptions_part2_peripheral_IRQs/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/13_exceptions_part2_peripheral_IRQs/Cargo.lock b/13_exceptions_part2_peripheral_IRQs/Cargo.lock new file mode 100644 index 000000000..ad1e8660e --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/Cargo.lock @@ -0,0 +1,84 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.13.0" +dependencies = [ + "aarch64-cpu", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/13_exceptions_part2_peripheral_IRQs/Cargo.toml b/13_exceptions_part2_peripheral_IRQs/Cargo.toml new file mode 100644 index 000000000..6480a7276 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +members = [ + "libraries/*", + "kernel" +] + +[profile.release] +lto = true diff --git a/13_exceptions_part2_peripheral_IRQs/Makefile b/13_exceptions_part2_peripheral_IRQs/Makefile new file mode 100644 index 000000000..4e2efeff3 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/Makefile @@ -0,0 +1,334 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/13_exceptions_part2_peripheral_IRQs/README.md b/13_exceptions_part2_peripheral_IRQs/README.md new file mode 100644 index 000000000..5be659147 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/README.md @@ -0,0 +1,3246 @@ +# Tutorial 13 - Exceptions Part 2: Peripheral IRQs + +## tl;dr + +- We write `device drivers` for the two interrupt controllers on the **Raspberry Pi 3** (`Broadcom` + custom controller) and **Pi 4** (`ARM` Generic Interrupt Controller v2, `GICv2`). +- Modularity is ensured by interfacing everything through a trait named `IRQManager`. +- Handling for our first peripheral IRQs is implemented: The `UART`'s receive IRQs. + +![Header](../doc/14_header.png) + +## Table of Contents + +- [Introduction](#introduction) +- [Different Controllers: A Usecase for Abstraction](#different-controllers-a-usecase-for-abstraction) +- [New Challenges: Reentrancy](#new-challenges-reentrancy) +- [Implementation](#implementation) + * [The Kernel's Interfaces for Interrupt Handling](#the-kernels-interfaces-for-interrupt-handling) + + [Uniquely Identifying an IRQ](#uniquely-identifying-an-irq) + - [The BCM IRQ Number Scheme](#the-bcm-irq-number-scheme) + - [The GICv2 IRQ Number Scheme](#the-gicv2-irq-number-scheme) + + [Registering IRQ Handlers](#registering-irq-handlers) + + [Handling Pending IRQs](#handling-pending-irqs) + * [Reentrancy: What to protect?](#reentrancy-what-to-protect) + * [The Interrupt Controller Device Drivers](#the-interrupt-controller-device-drivers) + + [The BCM Driver (Pi 3)](#the-bcm-driver-pi-3) + - [Peripheral Controller Register Access](#peripheral-controller-register-access) + - [The IRQ Handler Table](#the-irq-handler-table) + + [The GICv2 Driver (Pi 4)](#the-gicv2-driver-pi-4) + - [GICC Details](#gicc-details) + - [GICD Details](#gicd-details) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +In [tutorial 11], we laid the groundwork for exception handling from the processor architecture +side. Handler stubs for the different exception types were set up, and a first glimpse at exception +handling was presented by causing a `synchronous` exception by means of a `page fault`. + +[tutorial 11]: ../11_exceptions_part1_groundwork + +In this tutorial, we will add a first level of support for one of the three types of `asynchronous` +exceptions that are defined for `AArch64`: `IRQs`. The overall goal for this tutorial is to get rid +of the busy-loop at the end of our current `kernel_main()` function, which actively polls the +`UART` for newly received characters. Instead, we will let the processor idle and wait for the +`UART`'s RX IRQs, which indicate that new characters were received. A respective `IRQ` service +routine, provided by the `UART` driver, will run in response to the `IRQ` and print the characters. + +## Different Controllers: A Usecase for Abstraction + +One very exciting aspect of this tutorial is that the `Pi 3` and the `Pi 4` feature completely +different interrupt controllers. This is also a first in all of the tutorial series. Until now, both +Raspberrys did not need differentiation with respect to their devices. + +The `Pi 3` has a very simple custom controller made by Broadcom (BCM), the manufacturer of the Pi's +`System-on-Chip`. The `Pi 4` features an implementation of `ARM`'s Generic Interrupt Controller +version 2 (`GICv2`). Since ARM's GIC controllers are the prevalent interrupt controllers in ARM +application procesors, it is very beneficial to finally have it on the Raspberry Pi. It will enable +people to learn about one of the most common building blocks in ARM-based embedded computing. + +This also means that we can finally make full use of all the infrastructure for abstraction that we +prepared already. We will design an `IRQManager` interface trait and implement it in both controller +drivers. The generic part of our `kernel` code will only be exposed to this trait (compare to the +diagram in the [tl;dr] section). This common idiom of *program to an interface, not an +implementation* enables a clean abstraction and makes the code modular and pluggable. + +[tl;dr]: #tldr + +## New Challenges: Reentrancy + +Enabling interrupts also poses new challenges with respect to protecting certain code sections in +the kernel from being [re-entered]. Please read the linked article for background on that topic. + +[re-entered]: https://en.wikipedia.org/wiki/Reentrancy_(computing) + +Our `kernel` is still running on a single core. For this reason, we are still using our `NullLock` +pseudo-locks for `Critical Sections` or `shared resources`, instead of real `Spinlocks`. Hence, +interrupt handling at this point in time does not put us at risk of running into one of those +dreaded `deadlocks`, which is one of several side-effects that reentrancy can cause. For example, a +`deadlock` because of interrupts can happen happen when the executing CPU core has locked a +`Spinlock` at the beginning of a function, an IRQ happens, and the IRQ service routine is trying to +execute the same function. Since the lock is already locked, the core would spin forever waiting for +it to be released. + +There is no straight-forward way to tell if a function is `reentrantcy`-safe or not. It usually +needs careful manual checking to conclude. Even though it might be technically safe to `re-enter` a +function, sometimes you don't want that to happen for functional reasons. For example, printing of a +string should not be interrupted by a an interrupt service routine that starts printing another +string, so that the output mixes. In the course of this tutorial, we will check and see where we +want to protect against `reentrancy`. + +## Implementation + +Okay, let's start. The following sections cover the the implementation in a top-down fashion, +starting with the trait that interfaces all the `kernel` components to each other. + +### The Kernel's Interfaces for Interrupt Handling + +First, we design the `IRQManager` trait that interrupt controller drivers must implement. The +minimal set of functionality that we need for starters is: + +1. Registering an IRQ `handler` for a given IRQ `number`. +2. Enabling an IRQ (from the controller side). +3. Handling pending IRQs. +4. Printing the list of registered IRQ handlers. + +The trait is defined as `exception::asynchronous::interface::IRQManager`: + +```rust +pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} +} +``` + +#### Uniquely Identifying an IRQ + +The first member of the trait is the [associated type] `IRQNumberType`. The following explains why +we make it customizable for the implementor and do not define the type as a plain integer right +away. + +Interrupts can generally be characterizied with the following properties: + +[associated type]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types + +1. Software-generated vs hardware-generated. +2. Private vs shared. + +Different interrupt controllers take different approaches at categorizing and numbering IRQs that +have one or the other property. Often times, this leads to situations where a plain integer does not +suffice to uniquely identify an IRQ, and makes it necessary to encode additional information in the +used type. Letting the respective interrupt controller driver define `IRQManager::IRQNumberType` +itself addresses this issue. The rest of the `BSP` must then conditionally use this type. + +##### The BCM IRQ Number Scheme + +The `BCM` controller of the `Raspberry Pi 3`, for example, is composed of two functional parts: A +**local** controller and a **peripheral** controller. The BCM's **local controller** handles all +`private` IRQs, which means private SW-generated IRQs and IRQs of private HW devices. An example for +the latter would be the `ARMv8` timer. Each CPU core has its own private instance of it. The BCM's +**peripheral controller** handles all IRQs of `non-private` HW devices such as the `UART` (if those +IRQs can be declared as `shared` according to our taxonomy above is a different discussion, because +the BCM controller allows these HW interrupts to be routed to _only one CPU core at a time_). + +The IRQ numbers of the BCM **local controller** range from `0..11`. The numbers of the **peripheral +controller** range from `0..63`. This demonstrates why a primitive integer type would not be +sufficient to uniquely encode the IRQs, because their ranges overlap. In the driver for the `BCM` +controller, we therefore define the associated type as follows: + +```rust +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} +``` + +The type `BoundedUsize` is a newtype around an `usize` that uses a [const generic] to ensure that +the value of the encapsulated IRQ number is in the allowed range (e.g. `0..MAX_LOCAL_IRQ_NUMBER` for +`LocalIRQ`, with `MAX_LOCAL_IRQ_NUMBER == 11`). + +[const generic]: https://github.com/rust-lang/rfcs/blob/master/text/2000-const-generics.md + +##### The GICv2 IRQ Number Scheme + +The `GICv2` in the `Raspberry Pi 4`, on the other hand, uses a different scheme. IRQ numbers `0..31` +are for `private` IRQs. Those are further subdivided into `SW-generated` (SGIs, `0..15`) and +`HW-generated` (PPIs, Private Peripheral Interrupts, `16..31`). Numbers `32..1019` are for `shared +hardware-generated` interrupts (SPI, Shared Peripheral Interrupts). + +There are no overlaps, so this scheme enables us to actually have a plain integer as a unique +identifier for the IRQs. We define the type as follows: + +```rust +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; +``` + +#### Registering IRQ Handlers + +To enable the controller driver to manage interrupt handling, it must know where to find respective +handlers, and it must know how to call them. For the latter, we define an `IRQHandler` trait in +`exception::asynchronous` that must be implemented by any SW entity that wants to handle IRQs: + +```rust +/// Implemented by types that handle IRQs. +pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; +} +``` + +The `PL011Uart` driver gets the honors for being our first driver to ever implement this trait. In +this tutorial, the `RX IRQ` and the `RX Timeout IRQ` will be configured. This means that the +`PL011Uart` will assert it's interrupt line when one of following conditions is met: + +1. `RX IRQ`: The RX FIFO fill level is equal or more than the configured trigger level (which will be 1/8 of + the total FIFO size in our case). +1. `RX Timeout IRQ`: The RX FIFO fill level is greater than zero, but less than the configured fill + level, and the characters have not been pulled for a certain amount of time. The exact time is + not documented in the respective `PL011Uart` datasheet. Usually, it is a single-digit multiple of + the time it takes to receive or transmit one character on the serial line. + + In the handler, our standard scheme of echoing any received characters back to the host is used: + +```rust +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} +``` + +Registering and enabling handlers in the interrupt controller is supposed to be done by the +respective drivers themselves. Therefore, we added a new function to the standard device driver +trait in `driver::interface::DeviceDriver` that must be implemented if IRQ handling is supported: + +```rust +/// Called by the kernel to register and enable the device's IRQ handler. +/// +/// Rust's type system will prevent a call to this function unless the calling instance +/// itself has static lifetime. +fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, +) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) +} +``` + +Here is the implementation for the `PL011Uart`: + +```rust +fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, +) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) +} +``` + +The `exception::asynchronous::irq_manager()` function used here returns a reference to an +implementor of the `IRQManager` trait. Since the implementation is supposed to be done by the +platform's interrupt controller, this call will redirect to the `kernel`'s instance of either the +driver for the `BCM` controller (`Raspberry Pi 3`) or the driver for the `GICv2` (`Pi 4`). We will +look into the implementation of the `register_handler()` function from the driver's perspective +later. The gist here is that the calls on `irq_manager()` will make the platform's interrupt +controller aware that the `UART` driver (i) wants to handle its interrupt and (ii) which function it +provides to do so. + +Also note how `irq_number` is supplied as a function argument and not hardcoded. The reason is that +the `UART` driver code is agnostic about the **IRQ numbers** that are associated to it. This is +vendor-supplied information and as such typically part of the Board Support Package (`BSP`). It can +vary from `BSP` to `BSP`, same like the board's memory map, which provides the `UART`'s MMIO +register addresses. + +With all this in place, we can finally let drivers register and enable their IRQ handlers with the +interrupt controller, and unmask IRQ reception on the boot CPU core during the kernel init phase. +The global `driver_manager` takes care of this in the function `init_drivers_and_irqs()` (before +this tutorial, the function's name was `init_drivers()`), where this happens as the third and last +step of initializing all registered device drivers: + +```rust +pub unsafe fn init_drivers_and_irqs(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + // omitted for brevity + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + // omitted for brevity + } + }); + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + self.for_each_descriptor(|descriptor| { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); +} +``` + + +In `main.rs`, IRQs are unmasked right afterwards, after which point IRQ handling is live: + +```rust +// Initialize all device drivers. +driver::driver_manager().init_drivers_and_irqs(); + +// Unmask interrupts on the boot CPU core. +exception::asynchronous::local_irq_unmask(); +``` + +#### Handling Pending IRQs + +Now that interrupts can happen, the `kernel` needs a way of requesting the interrupt controller +driver to handle pending interrupts. Therefore, implementors of the trait `IRQManager` must also +supply the following function: + +```rust +fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, +); +``` + +An important aspect of this function signature is that we want to ensure that IRQ handling is only +possible from IRQ context. Part of the reason is that this invariant allows us to make some implicit +assumptions (which might depend on the target architecture, though). For example, as we have learned +in [tutorial 11], in `AArch64`, _"all kinds of exceptions are turned off upon taking an exception, +so that by default, exception handlers can not get interrupted themselves"_ (note that an IRQ is an +exception). This is a useful property that relieves us from explicitly protecting IRQ handling from +being interrupted itself. Another reason would be that calling IRQ handling functions from arbitrary +execution contexts just doesn't make a lot of sense. + +[tutorial 11]: ../11_exceptions_part1_groundwork/ + +So in order to ensure that this function is only being called from IRQ context, we borrow a +technique that I first saw in the [Rust embedded WG]'s [bare-metal crate]. It uses Rust's type +system to create a "token" that is only valid for the duration of the IRQ context. We create it +directly at the top of the IRQ vector function in `_arch/aarch64/exception.rs`, and pass it on to +the the implementation of the trait's handling function: + +[Rust embedded WG]: https://github.com/rust-embedded/bare-metal +[bare-metal crate]: https://github.com/rust-embedded/bare-metal/blob/master/src/lib.rs#L20 + +```rust +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} +``` + +By requiring the caller of the function `handle_pending_irqs()` to provide this `IRQContext` token, +we can prevent that the same function is accidentally being called from somewhere else. It is +evident, though, that for this to work, it is the _user's responsibility_ to only ever create this +token from within an IRQ context. If you want to circumvent this on purpose, you can do it. + +### Reentrancy: What to protect? + +Now that interrupt handling is live, we need to think about `reentrancy`. At [the beginning of this +tutorial], we mused about the need to protect certain functions from being re-entered, and that it +is not straight-forward to identify all the places that need protection. + +[the beginning of this tutorial]: #new-challenges-reentrancy + +In this tutorial, we will keep this part short nonetheless by taking a better-safe-than-sorry +approach. In the past, we already made efforts to prepare parts of `shared resources` (e.g. global +device driver instances) to be protected against parallel access. We did so by wrapping them into +`NullLocks`, which we will upgrade to real `Spinlocks` once we boot secondary CPU cores. + +We can hook on that previous work and reason that anything that we wanted protected against parallel +access so far, we also want it protected against reentrancy now. Therefore, we upgrade all +`NullLocks` to `IRQSafeNullocks`: + +```rust +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} +``` + +The new part is that the call to `f(data)` is executed as a closure in +`exception::asynchronous::exec_with_irq_masked()`. Inside that function, IRQs on the executing CPU +core are masked before the `f(data)` is being executed, and restored afterwards: + +```rust +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} +``` + +The helper functions used here are defined in `src/_arch/aarch64/exception/asynchronous.rs`. + +### The Interrupt Controller Device Drivers + +The previous sections explained how the `kernel` uses the `IRQManager` trait. Now, let's have a look +at the driver-side of it in the Raspberry Pi `BSP`. We start with the Broadcom interrupt controller +featured in the `Pi 3`. + +#### The BCM Driver (Pi 3) + +As mentioned earlier, the `BCM` driver consists of two subcomponents, a **local** and a +**peripheral** controller. The local controller owns a bunch of configuration registers, among +others, the `routing` configuration for peripheral IRQs such as those from the `UART`. Peripheral +IRQs can be routed to _one core only_. In our case, we leave the default unchanged, which means +everything is routed to the boot CPU core. The image below depicts the `struct diagram` of the +driver implementation. + +![BCM Driver](../doc/14_BCM_driver.png) + +We have a top-level driver, which implements the `IRQManager` trait. _Only the top-level driver_ is +exposed to the rest of the `kernel`. The top-level itself has two members, representing the local +and the peripheral controller, respectively, which implement the `IRQManager` trait as well. This +design allows for easy forwarding of function calls from the top-level driver to one of the +subcontrollers. + +For this tutorial, we leave out implementation of the local controller, because we will only be +concerned with the peripheral `UART` IRQ. + +##### Peripheral Controller Register Access + +When writing a device driver for a kernel with exception handling and multi-core support, it is +always important to analyze what parts of the driver will need protection against reentrancy (we +talked about this earlier in this tutorial) and/or parallel execution of other driver parts. If a +driver function needs to follow a vendor-defined sequence of multiple register operations that +include `write operations`, this is usually a good hint that protection might be needed. But that is +only one of many examples. + +For the driver implementation in this tutorial, we are following a simple rule: Register read access +is deemed always safe. Write access is guarded by an `IRQSafeNullLock`, which means that we are safe +against `reentrancy` issues, and also in the future when the kernel will be running on multiple +cores, we can easily upgrade to a real spinlock, which serializes register write operations from +different CPU cores. + +In fact, for this tutorial, we probably would not have needed any protection yet, because all the +driver does is read from the `PENDING_*` registers for the `handle_pending_irqs()` implementation, +and writing to the `ENABLE_*` registers for the `enable()` implementation. However, the chosen +architecture will have us set up for future extensions, when more complex register manipulation +sequences might be needed. + +Since nothing complex is happening in the implementation, it is not covered in detail here. Please +refer to [the source of the **peripheral** controller] to check it out. + +[the source of the **peripheral** controller]: kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs + +##### The IRQ Handler Table + +Calls to `register_handler()` result in the driver inserting the provided handler reference in a +specific table (the handler reference is a member of `IRQDescriptor`): + +```rust +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; +``` + +One of the requirements for safe operation of the `kernel` is that those handlers are not +registered, removed or exchanged in the middle of an IRQ handling situation. This, again, is a +multi-core scenario where one core might look up a handler entry while another core is modifying the +same in parallel. + +While we want to allow drivers to take the decision of registering or not registering a handler at +runtime, there is no need to allow it for the _whole_ runtime of the kernel. It is fine to restrict +this option to the kernel `init phase`, at which only a single boot core runs and IRQs are masked. + +We introduce the so called `InitStateLock` for cases like that. From an API-perspective, it is a +special variant of a `Read/Write exclusion synchronization primitive`. RWLocks in the Rust standard +library [are characterized] as allowing _"a number of readers or at most one writer at any point in +time"_. For the `InitStateLock`, we only implement the `read()` and `write()` functions: + +[are characterized]: https://doc.rust-lang.org/std/sync/struct.RwLock.html + +```rust +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} +``` + +The `write()` function is guarded by two `assertions`. One ensures that IRQs are masked, the other +checks the `state::state_manager()` if the kernel is still in the init phase. The `State Manager` is +new since this tutorial, and implemented in `src/state.rs`. It provides atomic state transition and +reporting functions that are called when the kernel enters a new phase. In the current kernel, the +only call is happening before the transition from `kernel_init()` to `kernel_main()`: + +```rust +// Announce conclusion of the kernel_init() phase. +state::state_manager().transition_to_single_core_main(); +``` + +P.S.: Since the use case for the `InitStateLock` also applies to a few other places in the kernel +(for example, registering the system-wide console during early boot), `InitStateLock`s have been +incorporated in those other places as well. + +#### The GICv2 Driver (Pi 4) + +As we learned earlier, the ARM `GICv2` in the `Raspberry Pi 4` features a continuous interrupt +number range: +- IRQ numbers `0..31` represent IRQs that are private (aka local) to the respective processor core. +- IRQ numbers `32..1019` are for shared IRQs. + +The `GIC` has a so-called `Distributor`, the `GICD`, and a `CPU Interface`, the `GICC`. The `GICD`, +among other things, is used to enable IRQs and route them to one or more CPU cores. The `GICC` is +used by CPU cores to check which IRQs are pending, and to acknowledge them once they were handled. +There is one dedicated `GICC` for _each CPU core_. + +One neat thing about the `GICv2` is that any MMIO registers that are associated to core-private IRQs +are `banked`. That means that different CPU cores can assert the same MMIO address, but they will +end up accessing a core-private copy of the referenced register. This makes it very comfortable to +program the `GIC`, because this hardware design ensures that each core only ever gets access to its +own resources. Preventing one core to accidentally or willfully fiddle with the IRQ state of another +core must therefore not be enforced in software. + +In summary, this means that any registers in the `GICD` that deal with the core-private IRQ range +are banked. Since there is one `GICC` per CPU core, the whole thing is banked. This allows us to +design the following `struct diagram` for our driver implementation: + +![GICv2 Driver](../doc/14_GICv2_driver.png) + +The top-level struct is composed of a `GICD`, a `GICC` and a `HandlerTable`. The latter is +implemented identically as in the `Pi 3`. + +##### GICC Details + +Since the `GICC` is banked wholly, the top-level driver can directly forward any requests to it, +without worrying about concurrency issues for now. Note that this only works as long as the `GICC` +implementation is only accessing the banked `GICC` registers, and does not save any state in member +variables that are stored in `DRAM`. The two main duties of the `GICC` struct are to read the `IAR` +(Interrupt Acknowledge) register, which returns the number of the highest-priority pending IRQ, and +writing to the `EOIR` (End Of Interrupt) register, which tells the hardware that handling of an +interrupt is now concluded. + +##### GICD Details + +The `GICD` hardware block differentiates between `shared` and `banked` registers. As with the +`GICC`, we don't have to protect the banked registers against concurrent access. The shared +registers are wrapped into an `IRQSafeNullLock` again. The important parts of the `GICD` for this +tutorial are the `ITARGETSR[256]` and `ISENABLER[32]` register arrays. + +Each `ITARGETSR` is subdivided into four _bytes_. Each byte represents one IRQ, and stores a bitmask +that encodes all the `GICCs` to which the respective IRQ is forwarded. For example, +`ITARGETSR[0].byte0` would represent IRQ number 0, and `ITARGETSR[0].byte3` IRQ number 3. In the +`ISENABLER`, each _bit_ represents an IRQ. For example, `ISENABLER[0].bit3` is IRQ number 3. + +In summary, this means that `ITARGETSR[0..7]` and `ISENABLER[0]` represent the first 32 IRQs (the +banked ones), and as such, we split the register block into `shared` and `banked` parts accordingly +in `gicd.rs`: + +```rust +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} +``` + +As with the implementation of the BCM interrupt controller driver, we won't cover the remaining +parts in exhaustive detail. For that, please refer to [this folder] folder which contains all the +sources. + +[this folder]: kernel/src/bsp/device_driver/arm + +## Test it + +When you load the kernel, any keystroke results in echoing back the character by way of IRQ +handling. There is no more polling done at the end of `kernel_main()`, just waiting for events such +as IRQs: + +```rust +fn kernel_main() -> ! { + + // omitted for brevity + + info!("Echoing input now"); + cpu::wait_forever(); +} +``` + +Raspberry Pi 3: + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 66 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.822492] mingo version 0.13.0 +[ 0.822700] Booting on: Raspberry Pi 3 +[ 0.823155] MMU online. Special regions: +[ 0.823632] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data +[ 0.824650] 0x3f000000 - 0x4000ffff | 17 MiB | Dev RW PXN | Device MMIO +[ 0.825539] Current privilege level: EL1 +[ 0.826015] Exception handling state: +[ 0.826459] Debug: Masked +[ 0.826849] SError: Masked +[ 0.827239] IRQ: Unmasked +[ 0.827651] FIQ: Masked +[ 0.828041] Architectural timer resolution: 52 ns +[ 0.828615] Drivers loaded: +[ 0.828951] 1. BCM PL011 UART +[ 0.829373] 2. BCM GPIO +[ 0.829731] 3. BCM Interrupt Controller +[ 0.830262] Registered IRQ handlers: +[ 0.830695] Peripheral handler: +[ 0.831141] 57. BCM PL011 UART +[ 0.831649] Echoing input now +``` + +Raspberry Pi 4: + +```console +$ BSP=rpi4 make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 4 + +[ML] Requesting binary +[MP] ⏩ Pushing 73 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.886853] mingo version 0.13.0 +[ 0.886886] Booting on: Raspberry Pi 4 +[ 0.887341] MMU online. Special regions: +[ 0.887818] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data +[ 0.888836] 0xfe000000 - 0xff84ffff | 25 MiB | Dev RW PXN | Device MMIO +[ 0.889725] Current privilege level: EL1 +[ 0.890201] Exception handling state: +[ 0.890645] Debug: Masked +[ 0.891035] SError: Masked +[ 0.891425] IRQ: Unmasked +[ 0.891837] FIQ: Masked +[ 0.892227] Architectural timer resolution: 18 ns +[ 0.892801] Drivers loaded: +[ 0.893137] 1. BCM PL011 UART +[ 0.893560] 2. BCM GPIO +[ 0.893917] 3. GICv2 (ARM Generic Interrupt Controller v2) +[ 0.894654] Registered IRQ handlers: +[ 0.895087] Peripheral handler: +[ 0.895534] 153. BCM PL011 UART +[ 0.896042] Echoing input now +``` + +## Diff to previous +```diff + +diff -uNr 12_integrated_testing/kernel/Cargo.toml 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml +--- 12_integrated_testing/kernel/Cargo.toml ++++ 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.12.0" ++version = "0.13.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 12_integrated_testing/kernel/src/_arch/aarch64/cpu/smp.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs +--- 12_integrated_testing/kernel/src/_arch/aarch64/cpu/smp.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs +@@ -0,0 +1,30 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Architectural symmetric multiprocessing. ++//! ++//! # Orientation ++//! ++//! Since arch modules are imported into generic modules using the path attribute, the path of this ++//! file is: ++//! ++//! crate::cpu::smp::arch_smp ++ ++use aarch64_cpu::registers::*; ++use tock_registers::interfaces::Readable; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Return the executing core's id. ++#[inline(always)] ++pub fn core_id() -> T ++where ++ T: From, ++{ ++ const CORE_MASK: u64 = 0b11; ++ ++ T::from((MPIDR_EL1.get() & CORE_MASK) as u8) ++} + +diff -uNr 12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs +--- 12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs +@@ -12,12 +12,17 @@ + //! crate::exception::asynchronous::arch_asynchronous + + use aarch64_cpu::registers::*; +-use tock_registers::interfaces::Readable; ++use core::arch::asm; ++use tock_registers::interfaces::{Readable, Writeable}; + + //-------------------------------------------------------------------------------------------------- + // Private Definitions + //-------------------------------------------------------------------------------------------------- + ++mod daif_bits { ++ pub const IRQ: u8 = 0b0010; ++} ++ + trait DaifField { + fn daif_field() -> tock_registers::fields::Field; + } +@@ -66,6 +71,60 @@ + // Public Code + //-------------------------------------------------------------------------------------------------- + ++/// Returns whether IRQs are masked on the executing core. ++pub fn is_local_irq_masked() -> bool { ++ !is_masked::() ++} ++ ++/// Unmask IRQs on the executing core. ++/// ++/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. ++/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: ++/// ++/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional ++/// synchronization." ++#[inline(always)] ++pub fn local_irq_unmask() { ++ unsafe { ++ asm!( ++ "msr DAIFClr, {arg}", ++ arg = const daif_bits::IRQ, ++ options(nomem, nostack, preserves_flags) ++ ); ++ } ++} ++ ++/// Mask IRQs on the executing core. ++#[inline(always)] ++pub fn local_irq_mask() { ++ unsafe { ++ asm!( ++ "msr DAIFSet, {arg}", ++ arg = const daif_bits::IRQ, ++ options(nomem, nostack, preserves_flags) ++ ); ++ } ++} ++ ++/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). ++#[inline(always)] ++pub fn local_irq_mask_save() -> u64 { ++ let saved = DAIF.get(); ++ local_irq_mask(); ++ ++ saved ++} ++ ++/// Restore the interrupt mask bits (DAIF) using the callee's argument. ++/// ++/// # Invariant ++/// ++/// - No sanity checks on the input. ++#[inline(always)] ++pub fn local_irq_restore(saved: u64) { ++ DAIF.set(saved); ++} ++ + /// Print the AArch64 exceptions status. + #[rustfmt::skip] + pub fn print_state() { + +diff -uNr 12_integrated_testing/kernel/src/_arch/aarch64/exception.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs +--- 12_integrated_testing/kernel/src/_arch/aarch64/exception.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs +@@ -11,6 +11,7 @@ + //! + //! crate::exception::arch_exception + ++use crate::exception; + use aarch64_cpu::{asm::barrier, registers::*}; + use core::{arch::global_asm, cell::UnsafeCell, fmt}; + use tock_registers::{ +@@ -102,8 +103,9 @@ + } + + #[no_mangle] +-extern "C" fn current_elx_irq(e: &mut ExceptionContext) { +- default_exception_handler(e); ++extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { ++ let token = unsafe { &exception::asynchronous::IRQContext::new() }; ++ exception::asynchronous::irq_manager().handle_pending_irqs(token); + } + + #[no_mangle] + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs +@@ -0,0 +1,141 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! GICC Driver - GIC CPU interface. ++ ++use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; ++use tock_registers::{ ++ interfaces::{Readable, Writeable}, ++ register_bitfields, register_structs, ++ registers::ReadWrite, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++register_bitfields! { ++ u32, ++ ++ /// CPU Interface Control Register ++ CTLR [ ++ Enable OFFSET(0) NUMBITS(1) [] ++ ], ++ ++ /// Interrupt Priority Mask Register ++ PMR [ ++ Priority OFFSET(0) NUMBITS(8) [] ++ ], ++ ++ /// Interrupt Acknowledge Register ++ IAR [ ++ InterruptID OFFSET(0) NUMBITS(10) [] ++ ], ++ ++ /// End of Interrupt Register ++ EOIR [ ++ EOIINTID OFFSET(0) NUMBITS(10) [] ++ ] ++} ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ pub RegisterBlock { ++ (0x000 => CTLR: ReadWrite), ++ (0x004 => PMR: ReadWrite), ++ (0x008 => _reserved1), ++ (0x00C => IAR: ReadWrite), ++ (0x010 => EOIR: ReadWrite), ++ (0x014 => @END), ++ } ++} ++ ++/// Abstraction for the associated MMIO registers. ++type Registers = MMIODerefWrapper; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Representation of the GIC CPU interface. ++pub struct GICC { ++ registers: Registers, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl GICC { ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ Self { ++ registers: Registers::new(mmio_start_addr), ++ } ++ } ++ ++ /// Accept interrupts of any priority. ++ /// ++ /// Quoting the GICv2 Architecture Specification: ++ /// ++ /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field ++ /// value." ++ /// ++ /// # Safety ++ /// ++ /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead ++ /// of `&mut self`. ++ pub fn priority_accept_all(&self) { ++ self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. ++ } ++ ++ /// Enable the interface - start accepting IRQs. ++ /// ++ /// # Safety ++ /// ++ /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead ++ /// of `&mut self`. ++ pub fn enable(&self) { ++ self.registers.CTLR.write(CTLR::Enable::SET); ++ } ++ ++ /// Extract the number of the highest-priority pending IRQ. ++ /// ++ /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. ++ /// ++ /// # Safety ++ /// ++ /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead ++ /// of `&mut self`. ++ #[allow(clippy::trivially_copy_pass_by_ref)] ++ pub fn pending_irq_number<'irq_context>( ++ &self, ++ _ic: &exception::asynchronous::IRQContext<'irq_context>, ++ ) -> usize { ++ self.registers.IAR.read(IAR::InterruptID) as usize ++ } ++ ++ /// Complete handling of the currently active IRQ. ++ /// ++ /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. ++ /// ++ /// To be called after `pending_irq_number()`. ++ /// ++ /// # Safety ++ /// ++ /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead ++ /// of `&mut self`. ++ #[allow(clippy::trivially_copy_pass_by_ref)] ++ pub fn mark_comleted<'irq_context>( ++ &self, ++ irq_number: u32, ++ _ic: &exception::asynchronous::IRQContext<'irq_context>, ++ ) { ++ self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs +@@ -0,0 +1,199 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! GICD Driver - GIC Distributor. ++//! ++//! # Glossary ++//! - SPI - Shared Peripheral Interrupt. ++ ++use crate::{ ++ bsp::device_driver::common::MMIODerefWrapper, state, synchronization, ++ synchronization::IRQSafeNullLock, ++}; ++use tock_registers::{ ++ interfaces::{Readable, Writeable}, ++ register_bitfields, register_structs, ++ registers::{ReadOnly, ReadWrite}, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++register_bitfields! { ++ u32, ++ ++ /// Distributor Control Register ++ CTLR [ ++ Enable OFFSET(0) NUMBITS(1) [] ++ ], ++ ++ /// Interrupt Controller Type Register ++ TYPER [ ++ ITLinesNumber OFFSET(0) NUMBITS(5) [] ++ ], ++ ++ /// Interrupt Processor Targets Registers ++ ITARGETSR [ ++ Offset3 OFFSET(24) NUMBITS(8) [], ++ Offset2 OFFSET(16) NUMBITS(8) [], ++ Offset1 OFFSET(8) NUMBITS(8) [], ++ Offset0 OFFSET(0) NUMBITS(8) [] ++ ] ++} ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ SharedRegisterBlock { ++ (0x000 => CTLR: ReadWrite), ++ (0x004 => TYPER: ReadOnly), ++ (0x008 => _reserved1), ++ (0x104 => ISENABLER: [ReadWrite; 31]), ++ (0x180 => _reserved2), ++ (0x820 => ITARGETSR: [ReadWrite; 248]), ++ (0xC00 => @END), ++ } ++} ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ BankedRegisterBlock { ++ (0x000 => _reserved1), ++ (0x100 => ISENABLER: ReadWrite), ++ (0x104 => _reserved2), ++ (0x800 => ITARGETSR: [ReadOnly; 8]), ++ (0x820 => @END), ++ } ++} ++ ++/// Abstraction for the non-banked parts of the associated MMIO registers. ++type SharedRegisters = MMIODerefWrapper; ++ ++/// Abstraction for the banked parts of the associated MMIO registers. ++type BankedRegisters = MMIODerefWrapper; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Representation of the GIC Distributor. ++pub struct GICD { ++ /// Access to shared registers is guarded with a lock. ++ shared_registers: IRQSafeNullLock, ++ ++ /// Access to banked registers is unguarded. ++ banked_registers: BankedRegisters, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl SharedRegisters { ++ /// Return the number of IRQs that this HW implements. ++ #[inline(always)] ++ fn num_irqs(&mut self) -> usize { ++ // Query number of implemented IRQs. ++ // ++ // Refer to GICv2 Architecture Specification, Section 4.3.2. ++ ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 ++ } ++ ++ /// Return a slice of the implemented ITARGETSR. ++ #[inline(always)] ++ fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { ++ assert!(self.num_irqs() >= 36); ++ ++ // Calculate the max index of the shared ITARGETSR array. ++ // ++ // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS ++ // register has four entries, so shift right by two. Subtract one because we start ++ // counting at zero. ++ let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; ++ ++ // Rust automatically inserts slice range sanity check, i.e. max >= min. ++ &self.ITARGETSR[0..spi_itargetsr_max_index] ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++use synchronization::interface::Mutex; ++ ++impl GICD { ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ Self { ++ shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), ++ banked_registers: BankedRegisters::new(mmio_start_addr), ++ } ++ } ++ ++ /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. ++ /// ++ /// Quoting the GICv2 Architecture Specification: ++ /// ++ /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that ++ /// corresponds only to the processor reading the register." ++ fn local_gic_target_mask(&self) -> u32 { ++ self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) ++ } ++ ++ /// Route all SPIs to the boot core and enable the distributor. ++ pub fn boot_core_init(&self) { ++ assert!( ++ state::state_manager().is_init(), ++ "Only allowed during kernel init phase" ++ ); ++ ++ // Target all SPIs to the boot core only. ++ let mask = self.local_gic_target_mask(); ++ ++ self.shared_registers.lock(|regs| { ++ for i in regs.implemented_itargets_slice().iter() { ++ i.write( ++ ITARGETSR::Offset3.val(mask) ++ + ITARGETSR::Offset2.val(mask) ++ + ITARGETSR::Offset1.val(mask) ++ + ITARGETSR::Offset0.val(mask), ++ ); ++ } ++ ++ regs.CTLR.write(CTLR::Enable::SET); ++ }); ++ } ++ ++ /// Enable an interrupt. ++ pub fn enable(&self, irq_num: &super::IRQNumber) { ++ let irq_num = irq_num.get(); ++ ++ // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 ++ // (division by 32) and arrive at the index for the respective ISENABLER[i]. ++ let enable_reg_index = irq_num >> 5; ++ let enable_bit: u32 = 1u32 << (irq_num modulo 32); ++ ++ // Check if we are handling a private or shared IRQ. ++ match irq_num { ++ // Private. ++ 0..=31 => { ++ let enable_reg = &self.banked_registers.ISENABLER; ++ enable_reg.set(enable_reg.get() | enable_bit); ++ } ++ // Shared. ++ _ => { ++ let enable_reg_index_shared = enable_reg_index - 1; ++ ++ self.shared_registers.lock(|regs| { ++ let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; ++ enable_reg.set(enable_reg.get() | enable_bit); ++ }); ++ } ++ } ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs +@@ -0,0 +1,226 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! GICv2 Driver - ARM Generic Interrupt Controller v2. ++//! ++//! The following is a collection of excerpts with useful information from ++//! - `Programmer's Guide for ARMv8-A` ++//! - `ARM Generic Interrupt Controller Architecture Specification` ++//! ++//! # Programmer's Guide - 10.6.1 Configuration ++//! ++//! The GIC is accessed as a memory-mapped peripheral. ++//! ++//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core ++//! uses the same address to access its own private CPU interface. ++//! ++//! It is not possible for a core to access the CPU interface of another core. ++//! ++//! # Architecture Specification - 10.6.2 Initialization ++//! ++//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized ++//! after reset before it can deliver interrupts to the core. ++//! ++//! In the Distributor, software must configure the priority, target, security and enable individual ++//! interrupts. The Distributor must subsequently be enabled through its control register ++//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption ++//! settings. ++//! ++//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This ++//! prepares the GIC to deliver interrupts to the core. ++//! ++//! Before interrupts are expected in the core, software prepares the core to take interrupts by ++//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in ++//! PSTATE, and setting the routing controls. ++//! ++//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. ++//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. ++//! Individual interrupts can also be disabled (or enabled) in the distributor. ++//! ++//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must ++//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the ++//! core's priority mask. ++//! ++//! # Architecture Specification - 1.4.2 Interrupt types ++//! ++//! - Peripheral interrupt ++//! - Private Peripheral Interrupt (PPI) ++//! - This is a peripheral interrupt that is specific to a single processor. ++//! - Shared Peripheral Interrupt (SPI) ++//! - This is a peripheral interrupt that the Distributor can route to any of a specified ++//! combination of processors. ++//! ++//! - Software-generated interrupt (SGI) ++//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The ++//! system uses SGIs for interprocessor communication. ++//! - An SGI has edge-triggered properties. The software triggering of the interrupt is ++//! equivalent to the edge transition of the interrupt request signal. ++//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt ++//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, ++//! identifies the processor that requested the interrupt. ++//! ++//! # Architecture Specification - 2.2.1 Interrupt IDs ++//! ++//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 ++//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by ++//! the Distributor. ++//! ++//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: ++//! - Interrupt numbers 32..1019 are used for SPIs. ++//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These ++//! interrupts are banked in the Distributor. ++//! - A banked interrupt is one where the Distributor can have multiple interrupts with the ++//! same ID. A banked interrupt is identified uniquely by its ID number and its associated ++//! CPU interface number. Of the banked interrupt IDs: ++//! - 00..15 SGIs ++//! - 16..31 PPIs ++ ++mod gicc; ++mod gicd; ++ ++use crate::{ ++ bsp::{self, device_driver::common::BoundedUsize}, ++ cpu, driver, exception, synchronization, ++ synchronization::InitStateLock, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++type HandlerTable = [Option>; ++ IRQNumber::MAX_INCLUSIVE + 1]; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. ++pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; ++ ++/// Representation of the GIC. ++pub struct GICv2 { ++ /// The Distributor. ++ gicd: gicd::GICD, ++ ++ /// The CPU Interface. ++ gicc: gicc::GICC, ++ ++ /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. ++ handler_table: InitStateLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl GICv2 { ++ const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. ++ ++ pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; ++ ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { ++ Self { ++ gicd: gicd::GICD::new(gicd_mmio_start_addr), ++ gicc: gicc::GICC::new(gicc_mmio_start_addr), ++ handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), ++ } ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++use synchronization::interface::ReadWriteEx; ++ ++impl driver::interface::DeviceDriver for GICv2 { ++ type IRQNumberType = IRQNumber; ++ ++ fn compatible(&self) -> &'static str { ++ Self::COMPATIBLE ++ } ++ ++ unsafe fn init(&self) -> Result<(), &'static str> { ++ if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { ++ self.gicd.boot_core_init(); ++ } ++ ++ self.gicc.priority_accept_all(); ++ self.gicc.enable(); ++ ++ Ok(()) ++ } ++} ++ ++impl exception::asynchronous::interface::IRQManager for GICv2 { ++ type IRQNumberType = IRQNumber; ++ ++ fn register_handler( ++ &self, ++ irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ++ ) -> Result<(), &'static str> { ++ self.handler_table.write(|table| { ++ let irq_number = irq_handler_descriptor.number().get(); ++ ++ if table[irq_number].is_some() { ++ return Err("IRQ handler already registered"); ++ } ++ ++ table[irq_number] = Some(irq_handler_descriptor); ++ ++ Ok(()) ++ }) ++ } ++ ++ fn enable(&self, irq_number: &Self::IRQNumberType) { ++ self.gicd.enable(irq_number); ++ } ++ ++ fn handle_pending_irqs<'irq_context>( ++ &'irq_context self, ++ ic: &exception::asynchronous::IRQContext<'irq_context>, ++ ) { ++ // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register ++ // (IAR). ++ let irq_number = self.gicc.pending_irq_number(ic); ++ ++ // Guard against spurious interrupts. ++ if irq_number > GICv2::MAX_IRQ_NUMBER { ++ return; ++ } ++ ++ // Call the IRQ handler. Panic if there is none. ++ self.handler_table.read(|table| { ++ match table[irq_number] { ++ None => panic!("No handler registered for IRQ {}", irq_number), ++ Some(descriptor) => { ++ // Call the IRQ handler. Panics on failure. ++ descriptor.handler().handle().expect("Error handling IRQ"); ++ } ++ } ++ }); ++ ++ // Signal completion of handling. ++ self.gicc.mark_comleted(irq_number as u32, ic); ++ } ++ ++ fn print_handler(&self) { ++ use crate::info; ++ ++ info!(" Peripheral handler:"); ++ ++ self.handler_table.read(|table| { ++ for (i, opt) in table.iter().skip(32).enumerate() { ++ if let Some(handler) = opt { ++ info!(" {: >3}. {}", i + 32, handler.name()); ++ } ++ } ++ }); ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/arm.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/arm.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs +@@ -0,0 +1,9 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! ARM driver top level. ++ ++pub mod gicv2; ++ ++pub use gicv2::*; + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +@@ -5,8 +5,8 @@ + //! GPIO Driver. + + use crate::{ +- bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, +- synchronization::NullLock, ++ bsp::device_driver::common::MMIODerefWrapper, driver, exception::asynchronous::IRQNumber, ++ synchronization, synchronization::IRQSafeNullLock, + }; + use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, +@@ -118,7 +118,7 @@ + + /// Representation of the GPIO HW. + pub struct GPIO { +- inner: NullLock, ++ inner: IRQSafeNullLock, + } + + //-------------------------------------------------------------------------------------------------- +@@ -200,7 +200,7 @@ + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { +- inner: NullLock::new(GPIOInner::new(mmio_start_addr)), ++ inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + +@@ -216,6 +216,8 @@ + use synchronization::interface::Mutex; + + impl driver::interface::DeviceDriver for GPIO { ++ type IRQNumberType = IRQNumber; ++ + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +@@ -0,0 +1,170 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Peripheral Interrupt Controller Driver. ++//! ++//! # Resources ++//! ++//! - ++ ++use super::{PendingIRQs, PeripheralIRQ}; ++use crate::{ ++ bsp::device_driver::common::MMIODerefWrapper, ++ exception, synchronization, ++ synchronization::{IRQSafeNullLock, InitStateLock}, ++}; ++use tock_registers::{ ++ interfaces::{Readable, Writeable}, ++ register_structs, ++ registers::{ReadOnly, WriteOnly}, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ WORegisterBlock { ++ (0x00 => _reserved1), ++ (0x10 => ENABLE_1: WriteOnly), ++ (0x14 => ENABLE_2: WriteOnly), ++ (0x18 => @END), ++ } ++} ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ RORegisterBlock { ++ (0x00 => _reserved1), ++ (0x04 => PENDING_1: ReadOnly), ++ (0x08 => PENDING_2: ReadOnly), ++ (0x0c => @END), ++ } ++} ++ ++/// Abstraction for the WriteOnly parts of the associated MMIO registers. ++type WriteOnlyRegisters = MMIODerefWrapper; ++ ++/// Abstraction for the ReadOnly parts of the associated MMIO registers. ++type ReadOnlyRegisters = MMIODerefWrapper; ++ ++type HandlerTable = [Option>; ++ PeripheralIRQ::MAX_INCLUSIVE + 1]; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Representation of the peripheral interrupt controller. ++pub struct PeripheralIC { ++ /// Access to write registers is guarded with a lock. ++ wo_registers: IRQSafeNullLock, ++ ++ /// Register read access is unguarded. ++ ro_registers: ReadOnlyRegisters, ++ ++ /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. ++ handler_table: InitStateLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl PeripheralIC { ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ Self { ++ wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), ++ ro_registers: ReadOnlyRegisters::new(mmio_start_addr), ++ handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), ++ } ++ } ++ ++ /// Query the list of pending IRQs. ++ fn pending_irqs(&self) -> PendingIRQs { ++ let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) ++ | u64::from(self.ro_registers.PENDING_1.get()); ++ ++ PendingIRQs::new(pending_mask) ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++use synchronization::interface::{Mutex, ReadWriteEx}; ++ ++impl exception::asynchronous::interface::IRQManager for PeripheralIC { ++ type IRQNumberType = PeripheralIRQ; ++ ++ fn register_handler( ++ &self, ++ irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ++ ) -> Result<(), &'static str> { ++ self.handler_table.write(|table| { ++ let irq_number = irq_handler_descriptor.number().get(); ++ ++ if table[irq_number].is_some() { ++ return Err("IRQ handler already registered"); ++ } ++ ++ table[irq_number] = Some(irq_handler_descriptor); ++ ++ Ok(()) ++ }) ++ } ++ ++ fn enable(&self, irq: &Self::IRQNumberType) { ++ self.wo_registers.lock(|regs| { ++ let enable_reg = if irq.get() <= 31 { ++ ®s.ENABLE_1 ++ } else { ++ ®s.ENABLE_2 ++ }; ++ ++ let enable_bit: u32 = 1 << (irq.get() modulo 32); ++ ++ // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable ++ // bits are unaffected. So we don't need read and OR'ing here. ++ enable_reg.set(enable_bit); ++ }); ++ } ++ ++ fn handle_pending_irqs<'irq_context>( ++ &'irq_context self, ++ _ic: &exception::asynchronous::IRQContext<'irq_context>, ++ ) { ++ self.handler_table.read(|table| { ++ for irq_number in self.pending_irqs() { ++ match table[irq_number] { ++ None => panic!("No handler registered for IRQ {}", irq_number), ++ Some(descriptor) => { ++ // Call the IRQ handler. Panics on failure. ++ descriptor.handler().handle().expect("Error handling IRQ"); ++ } ++ } ++ } ++ }) ++ } ++ ++ fn print_handler(&self) { ++ use crate::info; ++ ++ info!(" Peripheral handler:"); ++ ++ self.handler_table.read(|table| { ++ for (i, opt) in table.iter().enumerate() { ++ if let Some(handler) = opt { ++ info!(" {: >3}. {}", i, handler.name()); ++ } ++ } ++ }); ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +@@ -0,0 +1,152 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Interrupt Controller Driver. ++ ++mod peripheral_ic; ++ ++use crate::{ ++ bsp::device_driver::common::BoundedUsize, ++ driver, ++ exception::{self, asynchronous::IRQHandlerDescriptor}, ++}; ++use core::fmt; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Wrapper struct for a bitmask indicating pending IRQ numbers. ++struct PendingIRQs { ++ bitmask: u64, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; ++pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; ++ ++/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. ++#[derive(Copy, Clone)] ++#[allow(missing_docs)] ++pub enum IRQNumber { ++ Local(LocalIRQ), ++ Peripheral(PeripheralIRQ), ++} ++ ++/// Representation of the Interrupt Controller. ++pub struct InterruptController { ++ periph: peripheral_ic::PeripheralIC, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl PendingIRQs { ++ pub fn new(bitmask: u64) -> Self { ++ Self { bitmask } ++ } ++} ++ ++impl Iterator for PendingIRQs { ++ type Item = usize; ++ ++ fn next(&mut self) -> Option { ++ if self.bitmask == 0 { ++ return None; ++ } ++ ++ let next = self.bitmask.trailing_zeros() as usize; ++ self.bitmask &= self.bitmask.wrapping_sub(1); ++ Some(next) ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl fmt::Display for IRQNumber { ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ match self { ++ Self::Local(number) => write!(f, "Local({})", number), ++ Self::Peripheral(number) => write!(f, "Peripheral({})", number), ++ } ++ } ++} ++ ++impl InterruptController { ++ // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. ++ const MAX_LOCAL_IRQ_NUMBER: usize = 3; ++ const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; ++ ++ pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; ++ ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(periph_mmio_start_addr: usize) -> Self { ++ Self { ++ periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), ++ } ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++ ++impl driver::interface::DeviceDriver for InterruptController { ++ type IRQNumberType = IRQNumber; ++ ++ fn compatible(&self) -> &'static str { ++ Self::COMPATIBLE ++ } ++} ++ ++impl exception::asynchronous::interface::IRQManager for InterruptController { ++ type IRQNumberType = IRQNumber; ++ ++ fn register_handler( ++ &self, ++ irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ++ ) -> Result<(), &'static str> { ++ match irq_handler_descriptor.number() { ++ IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), ++ IRQNumber::Peripheral(pirq) => { ++ let periph_descriptor = IRQHandlerDescriptor::new( ++ pirq, ++ irq_handler_descriptor.name(), ++ irq_handler_descriptor.handler(), ++ ); ++ ++ self.periph.register_handler(periph_descriptor) ++ } ++ } ++ } ++ ++ fn enable(&self, irq: &Self::IRQNumberType) { ++ match irq { ++ IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), ++ IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), ++ } ++ } ++ ++ fn handle_pending_irqs<'irq_context>( ++ &'irq_context self, ++ ic: &exception::asynchronous::IRQContext<'irq_context>, ++ ) { ++ // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. ++ self.periph.handle_pending_irqs(ic) ++ } ++ ++ fn print_handler(&self) { ++ self.periph.print_handler(); ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +@@ -10,8 +10,11 @@ + //! - + + use crate::{ +- bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, +- synchronization::NullLock, ++ bsp::device_driver::common::MMIODerefWrapper, ++ console, cpu, driver, ++ exception::{self, asynchronous::IRQNumber}, ++ synchronization, ++ synchronization::IRQSafeNullLock, + }; + use core::fmt; + use tock_registers::{ +@@ -134,6 +137,52 @@ + ] + ], + ++ /// Interrupt FIFO Level Select Register. ++ IFLS [ ++ /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as ++ /// follows. ++ RXIFLSEL OFFSET(3) NUMBITS(5) [ ++ OneEigth = 0b000, ++ OneQuarter = 0b001, ++ OneHalf = 0b010, ++ ThreeQuarters = 0b011, ++ SevenEights = 0b100 ++ ] ++ ], ++ ++ /// Interrupt Mask Set/Clear Register. ++ IMSC [ ++ /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR ++ /// interrupt. ++ /// ++ /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. ++ /// - A write of 0 clears the mask. ++ RTIM OFFSET(6) NUMBITS(1) [ ++ Disabled = 0, ++ Enabled = 1 ++ ], ++ ++ /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. ++ /// ++ /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. ++ /// - A write of 0 clears the mask. ++ RXIM OFFSET(4) NUMBITS(1) [ ++ Disabled = 0, ++ Enabled = 1 ++ ] ++ ], ++ ++ /// Masked Interrupt Status Register. ++ MIS [ ++ /// Receive timeout masked interrupt status. Returns the masked interrupt state of the ++ /// UARTRTINTR interrupt. ++ RTMIS OFFSET(6) NUMBITS(1) [], ++ ++ /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR ++ /// interrupt. ++ RXMIS OFFSET(4) NUMBITS(1) [] ++ ], ++ + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. +@@ -152,7 +201,10 @@ + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), +- (0x34 => _reserved3), ++ (0x34 => IFLS: ReadWrite), ++ (0x38 => IMSC: ReadWrite), ++ (0x3C => _reserved3), ++ (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +@@ -179,7 +231,7 @@ + + /// Representation of the UART. + pub struct PL011Uart { +- inner: NullLock, ++ inner: IRQSafeNullLock, + } + + //-------------------------------------------------------------------------------------------------- +@@ -247,6 +299,14 @@ + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + ++ // Set RX FIFO fill level at 1/8. ++ self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); ++ ++ // Enable RX IRQ + RX timeout IRQ. ++ self.registers ++ .IMSC ++ .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); ++ + // Turn the UART on. + self.registers + .CR +@@ -337,7 +397,7 @@ + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { +- inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), ++ inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } + } +@@ -348,6 +408,8 @@ + use synchronization::interface::Mutex; + + impl driver::interface::DeviceDriver for PL011Uart { ++ type IRQNumberType = IRQNumber; ++ + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +@@ -357,6 +419,20 @@ + + Ok(()) + } ++ ++ fn register_and_enable_irq_handler( ++ &'static self, ++ irq_number: &Self::IRQNumberType, ++ ) -> Result<(), &'static str> { ++ use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; ++ ++ let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); ++ ++ irq_manager().register_handler(descriptor)?; ++ irq_manager().enable(irq_number); ++ ++ Ok(()) ++ } + } + + impl console::interface::Write for PL011Uart { +@@ -405,3 +481,24 @@ + } + + impl console::interface::All for PL011Uart {} ++ ++impl exception::asynchronous::interface::IRQHandler for PL011Uart { ++ fn handle(&self) -> Result<(), &'static str> { ++ self.inner.lock(|inner| { ++ let pending = inner.registers.MIS.extract(); ++ ++ // Clear all pending IRQs. ++ inner.registers.ICR.write(ICR::ALL::CLEAR); ++ ++ // Check for any kind of RX interrupt. ++ if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { ++ // Echo any received characters. ++ while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { ++ inner.write_char(c) ++ } ++ } ++ }); ++ ++ Ok(()) ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs +@@ -5,7 +5,11 @@ + //! BCM driver top level. + + mod bcm2xxx_gpio; ++#[cfg(feature = "bsp_rpi3")] ++mod bcm2xxx_interrupt_controller; + mod bcm2xxx_pl011_uart; + + pub use bcm2xxx_gpio::*; ++#[cfg(feature = "bsp_rpi3")] ++pub use bcm2xxx_interrupt_controller::*; + pub use bcm2xxx_pl011_uart::*; + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/common.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver/common.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs +@@ -4,7 +4,7 @@ + + //! Common device driver code. + +-use core::{marker::PhantomData, ops}; ++use core::{fmt, marker::PhantomData, ops}; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions +@@ -15,6 +15,10 @@ + phantom: PhantomData T>, + } + ++/// A wrapper type for usize with integrated range bound check. ++#[derive(Copy, Clone)] ++pub struct BoundedUsize(usize); ++ + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -36,3 +40,25 @@ + unsafe { &*(self.start_addr as *const _) } + } + } ++ ++impl BoundedUsize<{ MAX_INCLUSIVE }> { ++ pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; ++ ++ /// Creates a new instance if number <= MAX_INCLUSIVE. ++ pub const fn new(number: usize) -> Self { ++ assert!(number <= MAX_INCLUSIVE); ++ ++ Self(number) ++ } ++ ++ /// Return the wrapped number. ++ pub const fn get(self) -> usize { ++ self.0 ++ } ++} ++ ++impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ write!(f, "{}", self.0) ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs +--- 12_integrated_testing/kernel/src/bsp/device_driver.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs +@@ -4,9 +4,13 @@ + + //! Device driver. + ++#[cfg(feature = "bsp_rpi4")] ++mod arm; + #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] + mod bcm; + mod common; + ++#[cfg(feature = "bsp_rpi4")] ++pub use arm::*; + #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] + pub use bcm::*; + +diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi/driver.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs +--- 12_integrated_testing/kernel/src/bsp/raspberrypi/driver.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs +@@ -4,8 +4,12 @@ + + //! BSP driver support. + +-use super::memory::map::mmio; +-use crate::{bsp::device_driver, console, driver as generic_driver}; ++use super::{exception, memory::map::mmio}; ++use crate::{ ++ bsp::device_driver, ++ console, driver as generic_driver, ++ exception::{self as generic_exception}, ++}; + use core::sync::atomic::{AtomicBool, Ordering}; + + //-------------------------------------------------------------------------------------------------- +@@ -16,6 +20,14 @@ + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; + static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + ++#[cfg(feature = "bsp_rpi3")] ++static INTERRUPT_CONTROLLER: device_driver::InterruptController = ++ unsafe { device_driver::InterruptController::new(mmio::PERIPHERAL_IC_START) }; ++ ++#[cfg(feature = "bsp_rpi4")] ++static INTERRUPT_CONTROLLER: device_driver::GICv2 = ++ unsafe { device_driver::GICv2::new(mmio::GICD_START, mmio::GICC_START) }; ++ + //-------------------------------------------------------------------------------------------------- + // Private Code + //-------------------------------------------------------------------------------------------------- +@@ -33,21 +45,43 @@ + Ok(()) + } + ++/// This must be called only after successful init of the interrupt controller driver. ++fn post_init_interrupt_controller() -> Result<(), &'static str> { ++ generic_exception::asynchronous::register_irq_manager(&INTERRUPT_CONTROLLER); ++ ++ Ok(()) ++} ++ + fn driver_uart() -> Result<(), &'static str> { +- let uart_descriptor = +- generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); ++ let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( ++ &PL011_UART, ++ Some(post_init_uart), ++ Some(exception::asynchronous::irq_map::PL011_UART), ++ ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) + } + + fn driver_gpio() -> Result<(), &'static str> { +- let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); ++ let gpio_descriptor = ++ generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio), None); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) + } + ++fn driver_interrupt_controller() -> Result<(), &'static str> { ++ let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( ++ &INTERRUPT_CONTROLLER, ++ Some(post_init_interrupt_controller), ++ None, ++ ); ++ generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); ++ ++ Ok(()) ++} ++ + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -65,6 +99,7 @@ + + driver_uart()?; + driver_gpio()?; ++ driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) + +diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs +--- 12_integrated_testing/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs +@@ -0,0 +1,28 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! BSP asynchronous exception handling. ++ ++use crate::bsp; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Export for reuse in generic asynchronous.rs. ++pub use bsp::device_driver::IRQNumber; ++ ++#[cfg(feature = "bsp_rpi3")] ++pub(in crate::bsp) mod irq_map { ++ use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; ++ ++ pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); ++} ++ ++#[cfg(feature = "bsp_rpi4")] ++pub(in crate::bsp) mod irq_map { ++ use super::bsp::device_driver::IRQNumber; ++ ++ pub const PL011_UART: IRQNumber = IRQNumber::new(153); ++} + +diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi/exception.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs +--- 12_integrated_testing/kernel/src/bsp/raspberrypi/exception.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs +@@ -0,0 +1,7 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! BSP synchronous and asynchronous exception handling. ++ ++pub mod asynchronous; + +diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs +--- 12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs +@@ -73,10 +73,11 @@ + pub mod mmio { + use super::*; + +- pub const START: usize = 0x3F00_0000; +- pub const GPIO_START: usize = START + GPIO_OFFSET; +- pub const PL011_UART_START: usize = START + UART_OFFSET; +- pub const END_INCLUSIVE: usize = 0x4000_FFFF; ++ pub const START: usize = 0x3F00_0000; ++ pub const PERIPHERAL_IC_START: usize = START + 0x0000_B200; ++ pub const GPIO_START: usize = START + GPIO_OFFSET; ++ pub const PL011_UART_START: usize = START + UART_OFFSET; ++ pub const END_INCLUSIVE: usize = 0x4000_FFFF; + } + + /// Physical devices. +@@ -87,6 +88,8 @@ + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; ++ pub const GICD_START: usize = 0xFF84_1000; ++ pub const GICC_START: usize = 0xFF84_2000; + pub const END_INCLUSIVE: usize = 0xFF84_FFFF; + } + } + +diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi.rs +--- 12_integrated_testing/kernel/src/bsp/raspberrypi.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi.rs +@@ -6,6 +6,7 @@ + + pub mod cpu; + pub mod driver; ++pub mod exception; + pub mod memory; + + //-------------------------------------------------------------------------------------------------- + +diff -uNr 12_integrated_testing/kernel/src/console.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs +--- 12_integrated_testing/kernel/src/console.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs +@@ -6,7 +6,7 @@ + + mod null_console; + +-use crate::synchronization::{self, NullLock}; ++use crate::synchronization; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions +@@ -60,22 +60,22 @@ + // Global instances + //-------------------------------------------------------------------------------------------------- + +-static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = +- NullLock::new(&null_console::NULL_CONSOLE); ++static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = ++ InitStateLock::new(&null_console::NULL_CONSOLE); + + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- +-use synchronization::interface::Mutex; ++use synchronization::{interface::ReadWriteEx, InitStateLock}; + + /// Register a new console. + pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { +- CUR_CONSOLE.lock(|con| *con = new_console); ++ CUR_CONSOLE.write(|con| *con = new_console); + } + + /// Return a reference to the currently registered console. + /// + /// This is the global console used by all printing macros. + pub fn console() -> &'static dyn interface::All { +- CUR_CONSOLE.lock(|con| *con) ++ CUR_CONSOLE.read(|con| *con) + } + +diff -uNr 12_integrated_testing/kernel/src/cpu/smp.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs +--- 12_integrated_testing/kernel/src/cpu/smp.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs +@@ -0,0 +1,14 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2018-2023 Andre Richter ++ ++//! Symmetric multiprocessing. ++ ++#[cfg(target_arch = "aarch64")] ++#[path = "../_arch/aarch64/cpu/smp.rs"] ++mod arch_smp; ++ ++//-------------------------------------------------------------------------------------------------- ++// Architectural Public Reexports ++//-------------------------------------------------------------------------------------------------- ++pub use arch_smp::core_id; + +diff -uNr 12_integrated_testing/kernel/src/cpu.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs +--- 12_integrated_testing/kernel/src/cpu.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs +@@ -10,6 +10,8 @@ + + mod boot; + ++pub mod smp; ++ + //-------------------------------------------------------------------------------------------------- + // Architectural Public Reexports + //-------------------------------------------------------------------------------------------------- + +diff -uNr 12_integrated_testing/kernel/src/driver.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/driver.rs +--- 12_integrated_testing/kernel/src/driver.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/driver.rs +@@ -5,9 +5,10 @@ + //! Driver support. + + use crate::{ +- info, +- synchronization::{interface::Mutex, NullLock}, ++ exception, info, ++ synchronization::{interface::ReadWriteEx, InitStateLock}, + }; ++use core::fmt; + + //-------------------------------------------------------------------------------------------------- + // Private Definitions +@@ -15,9 +16,12 @@ + + const NUM_DRIVERS: usize = 5; + +-struct DriverManagerInner { ++struct DriverManagerInner ++where ++ T: 'static, ++{ + next_index: usize, +- descriptors: [Option; NUM_DRIVERS], ++ descriptors: [Option>; NUM_DRIVERS], + } + + //-------------------------------------------------------------------------------------------------- +@@ -28,6 +32,9 @@ + pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { ++ /// Different interrupt controllers might use different types for IRQ number. ++ type IRQNumberType: super::fmt::Display; ++ + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + +@@ -39,6 +46,21 @@ + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } ++ ++ /// Called by the kernel to register and enable the device's IRQ handler. ++ /// ++ /// Rust's type system will prevent a call to this function unless the calling instance ++ /// itself has static lifetime. ++ fn register_and_enable_irq_handler( ++ &'static self, ++ irq_number: &Self::IRQNumberType, ++ ) -> Result<(), &'static str> { ++ panic!( ++ "Attempt to enable IRQ {} for device {}, but driver does not support this", ++ irq_number, ++ self.compatible() ++ ) ++ } + } + } + +@@ -47,27 +69,37 @@ + + /// A descriptor for device drivers. + #[derive(Copy, Clone)] +-pub struct DeviceDriverDescriptor { +- device_driver: &'static (dyn interface::DeviceDriver + Sync), ++pub struct DeviceDriverDescriptor ++where ++ T: 'static, ++{ ++ device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, ++ irq_number: Option, + } + + /// Provides device driver management functions. +-pub struct DriverManager { +- inner: NullLock, ++pub struct DriverManager ++where ++ T: 'static, ++{ ++ inner: InitStateLock>, + } + + //-------------------------------------------------------------------------------------------------- + // Global instances + //-------------------------------------------------------------------------------------------------- + +-static DRIVER_MANAGER: DriverManager = DriverManager::new(); ++static DRIVER_MANAGER: DriverManager = DriverManager::new(); + + //-------------------------------------------------------------------------------------------------- + // Private Code + //-------------------------------------------------------------------------------------------------- + +-impl DriverManagerInner { ++impl DriverManagerInner ++where ++ T: 'static + Copy, ++{ + /// Create an instance. + pub const fn new() -> Self { + Self { +@@ -81,43 +113,48 @@ + // Public Code + //-------------------------------------------------------------------------------------------------- + +-impl DeviceDriverDescriptor { ++impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( +- device_driver: &'static (dyn interface::DeviceDriver + Sync), ++ device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, ++ irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, ++ irq_number, + } + } + } + + /// Return a reference to the global DriverManager. +-pub fn driver_manager() -> &'static DriverManager { ++pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER + } + +-impl DriverManager { ++impl DriverManager ++where ++ T: fmt::Display + Copy, ++{ + /// Create an instance. + pub const fn new() -> Self { + Self { +- inner: NullLock::new(DriverManagerInner::new()), ++ inner: InitStateLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. +- pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { +- self.inner.lock(|inner| { ++ pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { ++ self.inner.write(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. +- fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { +- self.inner.lock(|inner| { ++ fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { ++ self.inner.read(|inner| { + inner + .descriptors + .iter() +@@ -126,12 +163,12 @@ + }) + } + +- /// Fully initialize all drivers. ++ /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. +- pub unsafe fn init_drivers(&self) { ++ pub unsafe fn init_drivers_and_irqs(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { +@@ -150,6 +187,23 @@ + descriptor.device_driver.compatible(), + x + ); ++ } ++ } ++ }); ++ ++ // 3. After all post-init callbacks were done, the interrupt controller should be ++ // registered and functional. So let drivers register with it now. ++ self.for_each_descriptor(|descriptor| { ++ if let Some(irq_number) = &descriptor.irq_number { ++ if let Err(x) = descriptor ++ .device_driver ++ .register_and_enable_irq_handler(irq_number) ++ { ++ panic!( ++ "Error during driver interrupt handler registration: {}: {}", ++ descriptor.device_driver.compatible(), ++ x ++ ); + } + } + }); + +diff -uNr 12_integrated_testing/kernel/src/exception/asynchronous/null_irq_manager.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous/null_irq_manager.rs +--- 12_integrated_testing/kernel/src/exception/asynchronous/null_irq_manager.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous/null_irq_manager.rs +@@ -0,0 +1,42 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Null IRQ Manager. ++ ++use super::{interface, IRQContext, IRQHandlerDescriptor}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++pub struct NullIRQManager; ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl interface::IRQManager for NullIRQManager { ++ type IRQNumberType = super::IRQNumber; ++ ++ fn register_handler( ++ &self, ++ _descriptor: IRQHandlerDescriptor, ++ ) -> Result<(), &'static str> { ++ panic!("No IRQ Manager registered yet"); ++ } ++ ++ fn enable(&self, _irq_number: &Self::IRQNumberType) { ++ panic!("No IRQ Manager registered yet"); ++ } ++ ++ fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { ++ panic!("No IRQ Manager registered yet"); ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs +--- 12_integrated_testing/kernel/src/exception/asynchronous.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs +@@ -7,8 +7,184 @@ + #[cfg(target_arch = "aarch64")] + #[path = "../_arch/aarch64/exception/asynchronous.rs"] + mod arch_asynchronous; ++mod null_irq_manager; ++ ++use crate::{bsp, synchronization}; ++use core::marker::PhantomData; + + //-------------------------------------------------------------------------------------------------- + // Architectural Public Reexports + //-------------------------------------------------------------------------------------------------- +-pub use arch_asynchronous::print_state; ++pub use arch_asynchronous::{ ++ is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, ++ print_state, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Interrupt number as defined by the BSP. ++pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; ++ ++/// Interrupt descriptor. ++#[derive(Copy, Clone)] ++pub struct IRQHandlerDescriptor ++where ++ T: Copy, ++{ ++ /// The IRQ number. ++ number: T, ++ ++ /// Descriptive name. ++ name: &'static str, ++ ++ /// Reference to handler trait object. ++ handler: &'static (dyn interface::IRQHandler + Sync), ++} ++ ++/// IRQContext token. ++/// ++/// An instance of this type indicates that the local core is currently executing in IRQ ++/// context, aka executing an interrupt vector or subcalls of it. ++/// ++/// Concept and implementation derived from the `CriticalSection` introduced in ++/// ++#[derive(Clone, Copy)] ++pub struct IRQContext<'irq_context> { ++ _0: PhantomData<&'irq_context ()>, ++} ++ ++/// Asynchronous exception handling interfaces. ++pub mod interface { ++ ++ /// Implemented by types that handle IRQs. ++ pub trait IRQHandler { ++ /// Called when the corresponding interrupt is asserted. ++ fn handle(&self) -> Result<(), &'static str>; ++ } ++ ++ /// IRQ management functions. ++ /// ++ /// The `BSP` is supposed to supply one global instance. Typically implemented by the ++ /// platform's interrupt controller. ++ pub trait IRQManager { ++ /// The IRQ number type depends on the implementation. ++ type IRQNumberType: Copy; ++ ++ /// Register a handler. ++ fn register_handler( ++ &self, ++ irq_handler_descriptor: super::IRQHandlerDescriptor, ++ ) -> Result<(), &'static str>; ++ ++ /// Enable an interrupt in the controller. ++ fn enable(&self, irq_number: &Self::IRQNumberType); ++ ++ /// Handle pending interrupts. ++ /// ++ /// This function is called directly from the CPU's IRQ exception vector. On AArch64, ++ /// this means that the respective CPU core has disabled exception handling. ++ /// This function can therefore not be preempted and runs start to finish. ++ /// ++ /// Takes an IRQContext token to ensure it can only be called from IRQ context. ++ #[allow(clippy::trivially_copy_pass_by_ref)] ++ fn handle_pending_irqs<'irq_context>( ++ &'irq_context self, ++ ic: &super::IRQContext<'irq_context>, ++ ); ++ ++ /// Print list of registered handlers. ++ fn print_handler(&self) {} ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static CUR_IRQ_MANAGER: InitStateLock< ++ &'static (dyn interface::IRQManager + Sync), ++> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++use synchronization::{interface::ReadWriteEx, InitStateLock}; ++ ++impl IRQHandlerDescriptor ++where ++ T: Copy, ++{ ++ /// Create an instance. ++ pub const fn new( ++ number: T, ++ name: &'static str, ++ handler: &'static (dyn interface::IRQHandler + Sync), ++ ) -> Self { ++ Self { ++ number, ++ name, ++ handler, ++ } ++ } ++ ++ /// Return the number. ++ pub const fn number(&self) -> T { ++ self.number ++ } ++ ++ /// Return the name. ++ pub const fn name(&self) -> &'static str { ++ self.name ++ } ++ ++ /// Return the handler. ++ pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { ++ self.handler ++ } ++} ++ ++impl<'irq_context> IRQContext<'irq_context> { ++ /// Creates an IRQContext token. ++ /// ++ /// # Safety ++ /// ++ /// - This must only be called when the current core is in an interrupt context and will not ++ /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For ++ /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. ++ /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code ++ /// must not be able to influence the lifetime picked for this type, since that might cause it ++ /// to be inferred to `'static`. ++ #[inline(always)] ++ pub unsafe fn new() -> Self { ++ IRQContext { _0: PhantomData } ++ } ++} ++ ++/// Executes the provided closure while IRQs are masked on the executing core. ++/// ++/// While the function temporarily changes the HW state of the executing core, it restores it to the ++/// previous state before returning, so this is deemed safe. ++#[inline(always)] ++pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { ++ let saved = local_irq_mask_save(); ++ let ret = f(); ++ local_irq_restore(saved); ++ ++ ret ++} ++ ++/// Register a new IRQ manager. ++pub fn register_irq_manager( ++ new_manager: &'static (dyn interface::IRQManager + Sync), ++) { ++ CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); ++} ++ ++/// Return a reference to the currently registered IRQ manager. ++/// ++/// This is the IRQ manager used by the architectural interrupt handling code. ++pub fn irq_manager() -> &'static dyn interface::IRQManager { ++ CUR_IRQ_MANAGER.read(|manager| *manager) ++} + +diff -uNr 12_integrated_testing/kernel/src/lib.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs +--- 12_integrated_testing/kernel/src/lib.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs +@@ -138,6 +138,7 @@ + pub mod exception; + pub mod memory; + pub mod print; ++pub mod state; + pub mod time; + + //-------------------------------------------------------------------------------------------------- + +diff -uNr 12_integrated_testing/kernel/src/main.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs +--- 12_integrated_testing/kernel/src/main.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs +@@ -13,7 +13,7 @@ + #![no_main] + #![no_std] + +-use libkernel::{bsp, console, driver, exception, info, memory, time}; ++use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + + /// Early init code. + /// +@@ -23,7 +23,7 @@ + /// - The init calls in this function must appear in the correct order: + /// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, + /// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ +-/// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. ++/// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. + #[no_mangle] + unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; +@@ -40,8 +40,13 @@ + } + + // Initialize all device drivers. +- driver::driver_manager().init_drivers(); +- // println! is usable from here on. ++ driver::driver_manager().init_drivers_and_irqs(); ++ ++ // Unmask interrupts on the boot CPU core. ++ exception::asynchronous::local_irq_unmask(); ++ ++ // Announce conclusion of the kernel_init() phase. ++ state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +@@ -49,8 +54,6 @@ + + /// The main function running after the early init. + fn kernel_main() -> ! { +- use console::console; +- + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + +@@ -71,12 +74,9 @@ + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + +- info!("Echoing input now"); ++ info!("Registered IRQ handlers:"); ++ exception::asynchronous::irq_manager().print_handler(); + +- // Discard any spurious received characters before going into echo mode. +- console().clear_rx(); +- loop { +- let c = console().read_char(); +- console().write_char(c); +- } ++ info!("Echoing input now"); ++ cpu::wait_forever(); + } + +diff -uNr 12_integrated_testing/kernel/src/panic_wait.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs +--- 12_integrated_testing/kernel/src/panic_wait.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs +@@ -4,7 +4,7 @@ + + //! A panic handler that infinitely waits. + +-use crate::{cpu, println}; ++use crate::{cpu, exception, println}; + use core::panic::PanicInfo; + + //-------------------------------------------------------------------------------------------------- +@@ -59,6 +59,8 @@ + + #[panic_handler] + fn panic(info: &PanicInfo) -> ! { ++ exception::asynchronous::local_irq_mask(); ++ + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + +diff -uNr 12_integrated_testing/kernel/src/state.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs +--- 12_integrated_testing/kernel/src/state.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs +@@ -0,0 +1,92 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! State information about the kernel itself. ++ ++use core::sync::atomic::{AtomicU8, Ordering}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Different stages in the kernel execution. ++#[derive(Copy, Clone, Eq, PartialEq)] ++enum State { ++ /// The kernel starts booting in this state. ++ Init, ++ ++ /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of ++ /// `kernel_init()`, after all init calls are done). ++ SingleCoreMain, ++ ++ /// The kernel transitions to this state when it boots the secondary cores, aka switches ++ /// exectution mode to symmetric multiprocessing (SMP). ++ MultiCoreMain, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Maintains the kernel state and state transitions. ++pub struct StateManager(AtomicU8); ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static STATE_MANAGER: StateManager = StateManager::new(); ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Return a reference to the global StateManager. ++pub fn state_manager() -> &'static StateManager { ++ &STATE_MANAGER ++} ++ ++impl StateManager { ++ const INIT: u8 = 0; ++ const SINGLE_CORE_MAIN: u8 = 1; ++ const MULTI_CORE_MAIN: u8 = 2; ++ ++ /// Create a new instance. ++ pub const fn new() -> Self { ++ Self(AtomicU8::new(Self::INIT)) ++ } ++ ++ /// Return the current state. ++ fn state(&self) -> State { ++ let state = self.0.load(Ordering::Acquire); ++ ++ match state { ++ Self::INIT => State::Init, ++ Self::SINGLE_CORE_MAIN => State::SingleCoreMain, ++ Self::MULTI_CORE_MAIN => State::MultiCoreMain, ++ _ => panic!("Invalid KERNEL_STATE"), ++ } ++ } ++ ++ /// Return if the kernel is init state. ++ pub fn is_init(&self) -> bool { ++ self.state() == State::Init ++ } ++ ++ /// Transition from Init to SingleCoreMain. ++ pub fn transition_to_single_core_main(&self) { ++ if self ++ .0 ++ .compare_exchange( ++ Self::INIT, ++ Self::SINGLE_CORE_MAIN, ++ Ordering::Acquire, ++ Ordering::Relaxed, ++ ) ++ .is_err() ++ { ++ panic!("transition_to_single_core_main() called while state != Init"); ++ } ++ } ++} + +diff -uNr 12_integrated_testing/kernel/src/synchronization.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs +--- 12_integrated_testing/kernel/src/synchronization.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs +@@ -28,6 +28,21 @@ + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } ++ ++ /// A reader-writer exclusion type. ++ /// ++ /// The implementing object allows either a number of readers or at most one writer at any point ++ /// in time. ++ pub trait ReadWriteEx { ++ /// The type of encapsulated data. ++ type Data; ++ ++ /// Grants temporary mutable access to the encapsulated data. ++ fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; ++ ++ /// Grants temporary immutable access to the encapsulated data. ++ fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; ++ } + } + + /// A pseudo-lock for teaching purposes. +@@ -36,8 +51,18 @@ + /// other cores to the contained data. This part is preserved for later lessons. + /// + /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +-/// executing single-threaded, aka only running on a single core with interrupts disabled. +-pub struct NullLock ++/// executing on a single core. ++pub struct IRQSafeNullLock ++where ++ T: ?Sized, ++{ ++ data: UnsafeCell, ++} ++ ++/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. ++/// ++/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. ++pub struct InitStateLock + where + T: ?Sized, + { +@@ -48,10 +73,22 @@ + // Public Code + //-------------------------------------------------------------------------------------------------- + +-unsafe impl Send for NullLock where T: ?Sized + Send {} +-unsafe impl Sync for NullLock where T: ?Sized + Send {} ++unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} ++unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} ++ ++impl IRQSafeNullLock { ++ /// Create an instance. ++ pub const fn new(data: T) -> Self { ++ Self { ++ data: UnsafeCell::new(data), ++ } ++ } ++} ++ ++unsafe impl Send for InitStateLock where T: ?Sized + Send {} ++unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +-impl NullLock { ++impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { +@@ -63,8 +100,9 @@ + //------------------------------------------------------------------------------ + // OS Interface Code + //------------------------------------------------------------------------------ ++use crate::{exception, state}; + +-impl interface::Mutex for NullLock { ++impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { +@@ -72,6 +110,50 @@ + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + ++ // Execute the closure while IRQs are masked. ++ exception::asynchronous::exec_with_irq_masked(|| f(data)) ++ } ++} ++ ++impl interface::ReadWriteEx for InitStateLock { ++ type Data = T; ++ ++ fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { ++ assert!( ++ state::state_manager().is_init(), ++ "InitStateLock::write called after kernel init phase" ++ ); ++ assert!( ++ !exception::asynchronous::is_local_irq_masked(), ++ "InitStateLock::write called with IRQs unmasked" ++ ); ++ ++ let data = unsafe { &mut *self.data.get() }; ++ + f(data) + } ++ ++ fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { ++ let data = unsafe { &*self.data.get() }; ++ ++ f(data) ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Testing ++//-------------------------------------------------------------------------------------------------- ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ use test_macros::kernel_test; ++ ++ /// InitStateLock must be transparent. ++ #[kernel_test] ++ fn init_state_lock_is_transparent() { ++ use core::mem::size_of; ++ ++ assert_eq!(size_of::>(), size_of::()); ++ } + } + +diff -uNr 12_integrated_testing/kernel/tests/04_exception_irq_sanity.rs 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs +--- 12_integrated_testing/kernel/tests/04_exception_irq_sanity.rs ++++ 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs +@@ -0,0 +1,66 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! IRQ handling sanity tests. ++ ++#![feature(custom_test_frameworks)] ++#![no_main] ++#![no_std] ++#![reexport_test_harness_main = "test_main"] ++#![test_runner(libkernel::test_runner)] ++ ++use libkernel::{bsp, cpu, exception}; ++use test_macros::kernel_test; ++ ++#[no_mangle] ++unsafe fn kernel_init() -> ! { ++ bsp::driver::qemu_bring_up_console(); ++ ++ exception::handling_init(); ++ exception::asynchronous::local_irq_unmask(); ++ ++ test_main(); ++ ++ cpu::qemu_exit_success() ++} ++ ++/// Check that IRQ masking works. ++#[kernel_test] ++fn local_irq_mask_works() { ++ // Precondition: IRQs are unmasked. ++ assert!(exception::asynchronous::is_local_irq_masked()); ++ ++ exception::asynchronous::local_irq_mask(); ++ assert!(!exception::asynchronous::is_local_irq_masked()); ++ ++ // Restore earlier state. ++ exception::asynchronous::local_irq_unmask(); ++} ++ ++/// Check that IRQ unmasking works. ++#[kernel_test] ++fn local_irq_unmask_works() { ++ // Precondition: IRQs are masked. ++ exception::asynchronous::local_irq_mask(); ++ assert!(!exception::asynchronous::is_local_irq_masked()); ++ ++ exception::asynchronous::local_irq_unmask(); ++ assert!(exception::asynchronous::is_local_irq_masked()); ++} ++ ++/// Check that IRQ mask save is saving "something". ++#[kernel_test] ++fn local_irq_mask_save_works() { ++ // Precondition: IRQs are unmasked. ++ assert!(exception::asynchronous::is_local_irq_masked()); ++ ++ let first = exception::asynchronous::local_irq_mask_save(); ++ assert!(!exception::asynchronous::is_local_irq_masked()); ++ ++ let second = exception::asynchronous::local_irq_mask_save(); ++ assert_ne!(first, second); ++ ++ exception::asynchronous::local_irq_restore(first); ++ assert!(exception::asynchronous::is_local_irq_masked()); ++} + +``` diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml b/13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml new file mode 100644 index 000000000..3b04b97b6 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml @@ -0,0 +1,57 @@ +[package] +name = "mingo" +version = "0.13.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##-------------------------------------------------------------------------------------------------- +## Testing +##-------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/build.rs b/13_exceptions_part2_peripheral_IRQs/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..c80f3ebbc --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(crate::kernel_init as *const () as u64); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.s b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..f6df21236 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. x0 holds the function argument provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs new file mode 100644 index 000000000..491920389 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..730198009 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use crate::exception; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!(include_str!("exception.s")); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.s b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..91805ee7c --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 17 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..811ef138e --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..99ecaa2bf --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// # Safety +/// +/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". +static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + fn configure_translation_control(&self) { + let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI0::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG0::KiB_64 + + TCR_EL1::SH0::Inner + + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD0::EnableTTBR0Walks + + TCR_EL1::A1::TTBR0 + + TCR_EL1::T0SZ.val(t0sz) + + TCR_EL1::EPD1::DisableTTBR1Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Populate translation tables. + KERNEL_TABLES + .populate_tt_entries() + .map_err(MMUEnableError::Other)?; + + // Set the "Translation Table Base Register". + TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use core::{cell::UnsafeCell, ops::Range}; + use test_macros::kernel_test; + + /// Check if KERNEL_TABLES is in .bss. + #[kernel_test] + fn kernel_tables_in_bss() { + extern "Rust" { + static __bss_start: UnsafeCell; + static __bss_end_exclusive: UnsafeCell; + } + + let bss_range = unsafe { + Range { + start: __bss_start.get(), + end: __bss_end_exclusive.get(), + } + }; + let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; + + assert!(bss_range.contains(&kernel_tables_addr)); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..5e45a5fdf --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,320 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, memory, + memory::mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn phys_start_addr_u64(&self) -> u64; + fn phys_start_addr_usize(&self) -> usize; +} + +const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], +} + +/// A translation table type for the kernel space. +pub type KernelTranslationTable = FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +// The binary is still identity mapped, so we don't need to convert here. +impl StartAddr for [T; N] { + fn phys_start_addr_u64(&self) -> u64 { + self as *const T as u64 + } + + fn phys_start_addr_usize(&self) -> usize { + self as *const _ as usize + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl FixedSizeTranslationTable { + /// Create an instance. + pub const fn new() -> Self { + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + } + } + + /// Iterates over all static translation table entries and fills them at once. + /// + /// # Safety + /// + /// - Modifies a `static mut`. Ensure it only happens from here. + pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { + for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { + *l2_entry = + TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); + + for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { + let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); + + let (phys_output_addr, attribute_fields) = + bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; + + *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); + } + } + + Ok(()) + } + + /// The translation table's base address to be used for programming the MMU. + pub fn phys_base_address(&self) -> u64 { + self.lvl2.phys_start_addr_u64() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/time.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..2dfaec8d6 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(feature = "bsp_rpi4")] +mod arm; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs new file mode 100644 index 000000000..8d1cbfbd8 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs new file mode 100644 index 000000000..d8744fec4 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, synchronization, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs new file mode 100644 index 000000000..ce8ffa72f --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs new file mode 100644 index 000000000..1d528ca5e --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num % 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..7b7c288b7 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..353bcc8ca --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, exception::asynchronous::IRQNumber, + synchronization, synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs new file mode 100644 index 000000000..dfcbbaa78 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(periph_mmio_start_addr: usize) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.periph.print_handler(); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs new file mode 100644 index 000000000..b4c56f44e --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), + } + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() % 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..fbbbee560 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,504 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..90027e473 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{fmt, marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..30421dfa6 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/cpu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..d17272dda --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, +}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +#[cfg(feature = "bsp_rpi3")] +static INTERRUPT_CONTROLLER: device_driver::InterruptController = + unsafe { device_driver::InterruptController::new(mmio::PERIPHERAL_IC_START) }; + +#[cfg(feature = "bsp_rpi4")] +static INTERRUPT_CONTROLLER: device_driver::GICv2 = + unsafe { device_driver::GICv2::new(mmio::GICD_START, mmio::GICC_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the interrupt controller driver. +fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(&INTERRUPT_CONTROLLER); + + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + &PL011_UART, + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = + generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio), None); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +fn driver_interrupt_controller() -> Result<(), &'static str> { + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + &INTERRUPT_CONTROLLER, + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + console::register_console(&PL011_UART); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs new file mode 100644 index 000000000..a9eaa6ac4 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs new file mode 100644 index 000000000..776182fd0 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +#[cfg(feature = "bsp_rpi3")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; + + pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +#[cfg(feature = "bsp_rpi4")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::IRQNumber; + + pub const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..6d939889b --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..44cefe338 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | +//! | | +pub mod mmu; + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + /// The inclusive end address of the memory map. + /// + /// End address + 1 must be power of two. + /// + /// # Note + /// + /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for + /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. + /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. + /// + /// However, making this trade-off has the downside of making it possible for the CPU to assert a + /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on + /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. + pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const PERIPHERAL_IC_START: usize = START + 0x0000_B200; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0x4000_FFFF; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const GICD_START: usize = 0xFF84_1000; + pub const GICC_START: usize = 0xFF84_2000; + pub const END_INCLUSIVE: usize = 0xFF84_FFFF; + } +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_start() -> usize { + unsafe { __code_start.get() as usize } +} + +/// Exclusive end page address of the code segment. +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_end_exclusive() -> usize { + unsafe { __code_end_exclusive.get() as usize } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..563c8ba9b --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use super::map as memory_map; +use crate::memory::mmu::*; +use core::ops::RangeInclusive; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The kernel's address space defined by this BSP. +pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; + +const NUM_MEM_RANGES: usize = 2; + +/// The virtual memory layout. +/// +/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. +/// It is agnostic of the paging granularity that the architecture's MMU will use. +pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( + memory_map::END_INCLUSIVE, + [ + TranslationDescriptor { + name: "Kernel code and RO data", + virtual_range: code_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadOnly, + execute_never: false, + }, + }, + TranslationDescriptor { + name: "Device MMIO", + virtual_range: mmio_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + }, + ], +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn code_range_inclusive() -> RangeInclusive { + // Notice the subtraction to turn the exclusive end into an inclusive end. + #[allow(clippy::range_minus_one)] + RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) +} + +fn mmio_range_inclusive() -> RangeInclusive { + RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the virtual memory layout. +pub fn virt_mem_layout() -> &'static KernelVirtualLayout { + &LAYOUT +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check alignment of the kernel's virtual memory layout sections. + #[kernel_test] + fn virt_mem_layout_sections_are_64KiB_aligned() { + const SIXTYFOUR_KIB: usize = 65536; + + for i in LAYOUT.inner().iter() { + let start: usize = *(i.virtual_range)().start(); + let end: usize = *(i.virtual_range)().end() + 1; + + assert_eq!(start % SIXTYFOUR_KIB, 0); + assert_eq!(end % SIXTYFOUR_KIB, 0); + assert!(end >= start); + } + } + + /// Ensure the kernel's virtual memory layout is free of overlaps. + #[kernel_test] + fn virt_mem_layout_has_no_overlaps() { + let layout = virt_mem_layout().inner(); + + for (i, first) in layout.iter().enumerate() { + for second in layout.iter().skip(i + 1) { + let first_range = first.virtual_range; + let second_range = second.virtual_range; + + assert!(!first_range().contains(second_range().start())); + assert!(!first_range().contains(second_range().end())); + assert!(!second_range().contains(first_range().start())); + assert!(!second_range().contains(first_range().end())); + } + } + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/common.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/common.rs new file mode 100644 index 000000000..782a5da15 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/common.rs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs new file mode 100644 index 000000000..f03634649 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.read(|con| *con) +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/console/null_console.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs new file mode 100644 index 000000000..8716a918b --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +pub mod smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/boot.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs new file mode 100644 index 000000000..de612d589 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/driver.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/driver.rs new file mode 100644 index 000000000..2edf8b854 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/driver.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner +where + T: 'static, +{ + next_index: usize, + descriptors: [Option>; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager +where + T: 'static, +{ + inner: InitStateLock>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner +where + T: 'static + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + irq_number, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager +where + T: fmt::Display + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: InitStateLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.write(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.read(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + self.for_each_descriptor(|descriptor| { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/exception.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..2c874dd60 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous/null_irq_manager.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous/null_irq_manager.rs new file mode 100644 index 000000000..38919ffe4 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs new file mode 100644 index 000000000..a8783f6c3 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(int_roundings)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +mod panic_wait; +mod synchronization; + +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod state; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +#[cfg(not(test))] +extern "Rust" { + fn kernel_init() -> !; +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs new file mode 100644 index 000000000..e524322d8 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order: +/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, +/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ +/// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. +#[no_mangle] +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + exception::handling_init(); + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + panic!("MMU: {}", string); + } + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online. Special regions:"); + bsp::memory::mmu::virt_mem_layout().print_layout(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + + info!("Echoing input now"); + cpu::wait_forever(); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs new file mode 100644 index 000000000..6dd8f186b --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..7c7fc3974 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs @@ -0,0 +1,257 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. +//! +//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file +//! provides types for composing an architecture-agnostic description of the kernel's virtual memory +//! layout. +//! +//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` +//! function. +//! +//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and +//! install respective translation tables. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod translation_table; + +use crate::common; +use core::{fmt, ops::RangeInclusive}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_mmu::mmu; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Called by the kernel during early init. Supposed to take the translation tables from the + /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Architecture agnostic translation types. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum Translation { + Identity, + Offset(usize), +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// Architecture agnostic descriptor for a memory range. +#[allow(missing_docs)] +pub struct TranslationDescriptor { + pub name: &'static str, + pub virtual_range: fn() -> RangeInclusive, + pub physical_range_translation: Translation, + pub attribute_fields: AttributeFields, +} + +/// Type for expressing the kernel's virtual memory layout. +pub struct KernelVirtualLayout { + /// The last (inclusive) address of the address space. + max_virt_addr_inclusive: usize, + + /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. + inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +impl Default for AttributeFields { + fn default() -> AttributeFields { + AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + } + } +} + +/// Human-readable output of a TranslationDescriptor. +impl fmt::Display for TranslationDescriptor { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Call the function to which self.range points, and dereference the result, which causes + // Rust to copy the value. + let start = *(self.virtual_range)().start(); + let end = *(self.virtual_range)().end(); + let size = end - start + 1; + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match self.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match self.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if self.attribute_fields.execute_never { + "PXN" + } else { + "PX" + }; + + write!( + f, + " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", + start, end, size, unit, attr, acc_p, xn, self.name + ) + } +} + +impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { + /// Create a new instance. + pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { + Self { + max_virt_addr_inclusive: max, + inner: layout, + } + } + + /// For a virtual address, find and return the physical output address and corresponding + /// attributes. + /// + /// If the address is not found in `inner`, return an identity mapped default with normal + /// cacheable DRAM attributes. + pub fn virt_addr_properties( + &self, + virt_addr: usize, + ) -> Result<(usize, AttributeFields), &'static str> { + if virt_addr > self.max_virt_addr_inclusive { + return Err("Address out of range"); + } + + for i in self.inner.iter() { + if (i.virtual_range)().contains(&virt_addr) { + let output_addr = match i.physical_range_translation { + Translation::Identity => virt_addr, + Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), + }; + + return Ok((output_addr, i.attribute_fields)); + } + } + + Ok((virt_addr, AttributeFields::default())) + } + + /// Print the memory layout. + pub fn print_layout(&self) { + use crate::info; + + for i in self.inner.iter() { + info!("{}", i); + } + } + + #[cfg(test)] + pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { + &self.inner + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..1a2581aac --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_translation_table::KernelTranslationTable; diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs new file mode 100644 index 000000000..c6f3a9c7b --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, exception, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + _panic_exit() +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/print.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs new file mode 100644 index 000000000..6d99beedb --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs new file mode 100644 index 000000000..5740b63e5 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use crate::{exception, state}; + +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/src/time.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rb b/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..982c61708 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..3b065f13f --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..bf5b7d711 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + info!("MMU: {}", string); + cpu::qemu_exit_failure() + } + + info!("Writing beyond mapped area to address 9 GiB..."); + let big_addr: u64 = 9 * 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rb b/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..e22f49775 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + exception::handling_init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + info!("MMU: {}", string); + cpu::qemu_exit_failure() + } + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs new file mode 100644 index 000000000..e37896b8c --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/boot_test_string.rb b/13_exceptions_part2_peripheral_IRQs/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_exit_success/mod.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_wait_forever/mod.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/Cargo.toml b/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/src/lib.rs b/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/13_exceptions_part2_peripheral_IRQs/libraries/test-types/Cargo.toml b/13_exceptions_part2_peripheral_IRQs/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/13_exceptions_part2_peripheral_IRQs/libraries/test-types/src/lib.rs b/13_exceptions_part2_peripheral_IRQs/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/13_exceptions_part2_peripheral_IRQs/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/13_integrated_testing/.vscode/settings.json b/13_integrated_testing/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/13_integrated_testing/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/13_integrated_testing/Cargo.lock b/13_integrated_testing/Cargo.lock deleted file mode 100644 index 8930bc96d..000000000 --- a/13_integrated_testing/Cargo.lock +++ /dev/null @@ -1,91 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "qemu-exit", - "register", - "test-macros", - "test-types", -] - -[[package]] -name = "proc-macro2" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "qemu-exit" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73ae13954572c7ca0ec48ba9fe6a59c0392066eba62f8cb384ffd5addf538c5" - -[[package]] -name = "quote" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "syn" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "443b4178719c5a851e1bde36ce12da21d74a0e60b4d982ec3385a933c812f0f6" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "test-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "test-types", -] - -[[package]] -name = "test-types" -version = "0.1.0" - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" - -[[package]] -name = "unicode-xid" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" diff --git a/13_integrated_testing/Cargo.toml b/13_integrated_testing/Cargo.toml deleted file mode 100644 index 5d57cf357..000000000 --- a/13_integrated_testing/Cargo.toml +++ /dev/null @@ -1,55 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] -qemu-exit = "1.x.x" -test-types = { path = "test-types" } - -# Optional dependencies -register = { version = "1.x.x", features = ["no_std_unit_tests"], optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - -##-------------------------------------------------------------------------------------------------- -## Testing -##-------------------------------------------------------------------------------------------------- - -[dev-dependencies] -test-macros = { path = "test-macros" } - -# Unit tests are done in the library part of the kernel. -[lib] -name = "libkernel" -test = true - -# Disable unit tests for the kernel binary. -[[bin]] -name = "kernel" -test = false - -# List of tests without harness. -[[test]] -name = "00_console_sanity" -harness = false - -[[test]] -name = "02_exception_sync_page_fault" -harness = false diff --git a/13_integrated_testing/Makefile b/13_integrated_testing/Makefile deleted file mode 100644 index ad567bb5c..000000000 --- a/13_integrated_testing/Makefile +++ /dev/null @@ -1,176 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -# Testing-specific arguments -ifdef TEST - ifeq ($(TEST),unit) - TEST_ARG = --lib - else - TEST_ARG = --test $(TEST) - endif -endif - -QEMU_MISSING_STRING = "This board is not yet supported for QEMU." - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -TEST_CMD = cargo test $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot -DOCKER_ARG_DEV = --privileged -v /dev:/dev -DOCKER_ARG_NET = --network host - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) - DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) - DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -else - DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu test chainboot jtagboot openocd gdb gdb-opt0 \ - clippy clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu test: - @echo $(QEMU_MISSING_STRING) -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) - -define KERNEL_TEST_RUNNER - #!/usr/bin/env bash - - $(OBJCOPY_CMD) $$1 $$1.img - TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') - $(DOCKER_TEST) ruby tests/runner.rb $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY -endef - -export KERNEL_TEST_RUNNER -test: - @mkdir -p target - @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh - @chmod +x target/kernel_test_runner.sh - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) -endif - -chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -jtagboot: - @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) - -openocd: - @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) - -define gen_gdb - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC) $1" $(RUSTC_CMD) - @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) -endef - -gdb: - $(call gen_gdb,-C debuginfo=2) - -gdb-opt0: - $(call gen_gdb,-C debuginfo=2 -C opt-level=0) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/13_integrated_testing/README.md b/13_integrated_testing/README.md deleted file mode 100644 index 755576f95..000000000 --- a/13_integrated_testing/README.md +++ /dev/null @@ -1,2082 +0,0 @@ -# Tutorial 13 - Integrated Testing - -## tl;dr - -- We implement our own test framework using `Rust`'s [custom_test_frameworks] feature by enabling - `Unit Tests` and `Integration Tests` using `QEMU`. -- It is also possible to have test automation for the kernel's `console` (provided over `UART` in - our case): Sending strings/characters to the console and expecting specific answers in return. - - - -## Table of Contents - -- [Introduction](#introduction) -- [Challenges](#challenges) - * [Acknowledgements](#acknowledgements) -- [Implementation](#implementation) - * [Test Organization](#test-organization) - * [Enabling `custom_test_frameworks` for Unit Tests](#enabling-custom_test_frameworks-for-unit-tests) - + [The Unit Test Runner](#the-unit-test-runner) - + [Calling the Test `main()` Function](#calling-the-test-main-function) - * [Quitting QEMU with user-defined Exit Codes](#quitting-qemu-with-user-defined-exit-codes) - + [Exiting Unit Tests](#exiting-unit-tests) - * [Controlling Test Kernel Execution](#controlling-test-kernel-execution) - + [Wrapping QEMU Test Execution](#wrapping-qemu-test-execution) - * [Writing Unit Tests](#writing-unit-tests) - * [Integration Tests](#integration-tests) - + [Test Harness](#test-harness) - + [No Test Harness](#no-test-harness) - + [Overriding Panic Behavior](#overriding-panic-behavior) - * [Console Tests](#console-tests) -- [Test it](#test-it) -- [Diff to previous](#diff-to-previous) - -## Introduction - -Through the course of the previous tutorials, we silently started to adopt a kind of anti-pattern: -Using the kernel's main function to not only boot the target, but also test or showcase -functionality. For example: - - Stalling execution during boot to test the kernel's timekeeping code by spinning for 1 second. - - Willingly causing exceptions to see the exception handler running. - -The feature set of the kernel is now rich enough so that it makes sense to introduce proper testing -modeled after Rust's [native testing framework]. This tutorial extends our kernel with three basic -testing facilities: - - Classic `Unit Tests`. - - [Integration Tests] (self-contained tests stored in the `$CRATE/tests/` directory). - - `Console Tests`. These are integration tests acting on external stimuli - aka `console` input. - Sending strings/characters to the console and expecting specific answers in return. - -[native testing framework]: https://doc.rust-lang.org/book/ch11-00-testing.html - -## Challenges - -Testing Rust `#![no_std]` code like our kernel is, at the point of writing this tutorial, not an -easy endeavor. The short version is: We cannot use Rust's [native testing framework] straight away. -Utilizing the `#[test]` attribute macro and running `cargo test` would throw compilation errors, -because there are dependencies on the standard library. - -[native testing framework]: https://doc.rust-lang.org/book/ch11-00-testing.html - -We have to fall back to Rust's unstable [custom_test_frameworks] feature. It relieves us from -dependencies on the standard library, but comes at the cost of having a reduced feature set. Instead -of annotating functions with `#[test]`, the `#[test_case]` attribute must be used. Additionally, we -need to write a `test_runner` function, which is supposed to execute all the functions annotated -with `#[test_case]`. This is barely enough to get `Unit Tests` running, though. There will be some -more challenges that need solving for getting `Integration Tests` running as well. - -Please note that for automation purposes, all testing will be done in `QEMU` and not on real -hardware. - -[custom_test_frameworks]: https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html -[Integration Tests]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests - -### Acknowledgements - -On this occasion, kudos to [@phil-opp] for his x86-based [testing] article. It helped a lot in -putting together this tutorial. Please go ahead and read it for a different perspective and -additional insights. - -[testing]: https://os.phil-opp.com/testing - -## Implementation - -We introduce a new `Makefile` target: - -```console -$ make test -``` - -In essence, `make test` will execute `cargo test` instead of `cargo rustc`. The details will be -explained in due course. The rest of the tutorial will explain as chronologically as possible what -happens when `make test` aka `cargo test` runs. - -### Test Organization - -Until now, our kernel was a so-called `binary crate`. As [explained in the official Rust book], this -crate type disallows having `integration tests`. Quoting the book: - -[explained in the official Rust book]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests-for-binary-crates - -> If our project is a binary crate that only contains a _src/main.rs_ file and doesn’t have a -> _src/lib.rs_ file, we can’t create integration tests in the _tests_ directory and bring functions -> defined in the _src/main.rs_ file into scope with a `use` statement. Only library crates expose -> functions that other crates can use; binary crates are meant to be run on their own. - -> This is one of the reasons Rust projects that provide a binary have a straightforward -> _src/main.rs_ file that calls logic that lives in the _src/lib.rs_ file. Using that structure, -> integration tests _can_ test the library crate with `use` to make the important functionality -> available. If the important functionality works, the small amount of code in the _src/main.rs_ -> file will work as well, and that small amount of code doesn’t need to be tested. - -So let's do that first: We add a `lib.rs` to our crate that aggregates and exports the lion's share -of the kernel code. The `main.rs` file is stripped down to the minimum. It only keeps the -`kernel_init() -> !` and `kernel_main() -> !` functions, everything else is brought into scope with -`use` statements. - -Since it is not possible to use `kernel` as the name for both the library and the binary part of the -crate, new entries in `Cargo.toml` are needed to differentiate the names. What's more, `cargo test` -would try to compile and run `unit tests` for both. In our case, it will be sufficient to have all -the unit test code in `lib.rs`, so test generation for `main.rs` can be disabled in `Cargo.toml` as -well through the `test` flag: - -```toml -[lib] -name = "libkernel" -test = true - -[[bin]] -name = "kernel" -test = false -``` - -### Enabling `custom_test_frameworks` for Unit Tests - -In `lib.rs`, we add the following headers to get started with `custom_test_frameworks`: - -```rust -// Testing -#![cfg_attr(test, no_main)] -#![cfg_attr(test, feature(slice_ptr_range))] -#![feature(custom_test_frameworks)] -#![reexport_test_harness_main = "test_main"] -#![test_runner(crate::test_runner)] -``` - -Since this is a library now, we do not keep the `#![no_main]` inner attribute that `main.rs` has, -because a library has no `main()` entry function, so the attribute does not apply. When compiling -for testing, though, it is still needed. The reason is that `cargo test` basically turns `lib.rs` -into a binary again by inserting a generated `main()` function (which is then calling a function -that runs all the unit tests, but more about that in a second...). - -However, since our kernel code [overrides the compiler-inserted `main` shim] by way of using -`#![no_main]`, we need the same when `cargo test` is producing its test kernel binary. After all, -what we want is a minimal kernel that boots on the target and runs its own unit tests. Therefore, we -conditionally set this attribute (`#![cfg_attr(test, no_main)]`) when the `test` flag is set, which -it is when `cargo test` runs. - -[overrides the compiler-inserted `main` shim]: https://doc.rust-lang.org/unstable-book/language-features/lang-items.html?highlight=no_main#writing-an-executable-without-stdlib - -#### The Unit Test Runner - -The `#![test_runner(crate::test_runner)]` attribute declares the path of the test runner function -that we are supposed to provide. This is the one that will be called by the `cargo test` generated -`main()` function. Here is the implementation in `lib.rs`: - -```rust -/// The default runner for unit tests. -pub fn test_runner(tests: &[&test_types::UnitTest]) { - println!("Running {} tests", tests.len()); - println!("-------------------------------------------------------------------\n"); - for (i, test) in tests.iter().enumerate() { - print!("{:>3}. {:.<58}", i + 1, test.name); - - // Run the actual test. - (test.test_func)(); - - // Failed tests call panic!(). Execution reaches here only if the test has passed. - println!("[ok]") - } -} -``` - -The function signature shows that `test_runner` takes one argument: A slice of -`test_types::UnitTest` references. This type definition lives in an external crate stored at -`$ROOT/test_types`. It is external because the type is also needed for a self-made [procedural -macro] that we'll use to write unit tests, and procedural macros _have_ to live in their own crate. -So to avoid a circular dependency between kernel and proc-macro, this split was needed. Anyways, -here is the type definition: - -[procedural macro]: https://doc.rust-lang.org/reference/procedural-macros.html - -```rust -/// Unit test container. -pub struct UnitTest { - /// Name of the test. - pub name: &'static str, - - /// Function pointer to the test. - pub test_func: fn(), -} -``` - -A `UnitTest` provides a name and a classic function pointer to the unit test function. The -`test_runner` just iterates over the slice, prints the respective test's name and calls the test -function. - -The convetion is that as long as the test function does not `panic!`, the test was successful. - -#### Calling the Test `main()` Function - -The last of the attributes we added is `#![reexport_test_harness_main = "test_main"]`. Remember that -our kernel uses the `no_main` attribute, and that we also set it for the test compilation. We did -that because we wrote our own `_start()` function (in `aarch64.rs`), which kicks off the following -call chain during kernel boot: - -| | Function | File | -| - | - | - | -| 1. | `_start()` | `lib.rs` | -| 2. | (some more arch64 code) | `lib.rs` | -| 3. | `runtime_init()` | `lib.rs` | -| 4. | `kernel_init()` | `main.rs` | -| 5. | `kernel_main()` | `main.rs` | - -A function named `main` is never called. Hence, the `main()` function generated by `cargo test` -would be silently dropped, and therefore the tests would never be executed. As you can see, -`runtime_init()` is the last function residing in our carved-out `lib.rs`, and it calls into -`kernel_init()`. So in order to get the tests to execute, we add a test-environment version of -`kernel_init()` to `lib.rs` as well (conditional compilation ensures it is only present when the -test flag is set), and call the `cargo test` generated `main()` function from there. - -This is where `#![reexport_test_harness_main = "test_main"]` finally comes into picture. It declares -the name of the generated main function so that we can manually call it. Here is the final -implementation in `lib.rs`: - -```rust -/// The `kernel_init()` for unit tests. Called from `runtime_init()`. -#[cfg(test)] -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - test_main(); - - cpu::qemu_exit_success() -} -``` - -Note that we first call `bsp::console::qemu_bring_up_console()`. Since we are running all our tests -inside `QEMU`, we need to ensure that whatever peripheral implements the kernel's `console` -interface is initialized, so that we can print from our tests. If you recall [tutorial 03], bringing -up peripherals in `QEMU` might not need the full initialization as is needed on real hardware -(setting clocks, config registers, etc...) due to the abstractions in `QEMU`'s emulation code. So -this is an opportunity to cut down on setup code. - -[tutorial 03]: ../03_hacky_hello_world - -As a matter of fact, for the `Raspberrys`, nothing needs to be done and the function is empy. But -this might be different for other hardware emulated by QEMU, so it makes sense to introduce the -function now to make it easier in case new `BSPs` are added to the kernel in the future. - -Next, the reexported `test_main()` is called, which will call our `test_runner()` which finally -prints the unit test names and executes them. - -### Quitting QEMU with user-defined Exit Codes - -Let's recap where we are right now: - -We've enabled `custom_test_frameworks` in `lib.rs` to a point where, when using `make test`, the -code gets compiled to a test kernel binary that eventually executes all the (yet-to-be-defined) -`UnitTest` instances by executing all the way from `_start()` to our `test_runner()` function. - -Through mechanisms that are explained later, `cargo` will now instantiate a `QEMU` process that -exectues this test kernel. The question now is: How is test success/failure communicated to `cargo`? -Answer: `cargo` inspects `QEMU`'s [exit status]: - - - `0` translates to testing was successful. - - `non-0` means failure. - -Hence, we need a clever trick now so that our Rust kernel code can get `QEMU` to exit itself with an -exit status that the kernel code supplies. In [@phil-opp]'s testing article, you [learned how to do -this] for `x86 QEMU` systems by using a special `ISA` debug-exit device. Unfortunately, we can't -have that one for our `aarch64` system because it is not compatible. - -In our case, we can leverage the ARM [semihosting] emulation of `QEMU` and do a `SYS_EXIT` -semihosting call with an additional parameter for the exit code. I've written a separate crate, -[qemu-exit], to do this. So let us import it and utilize it in `_arch/aarch64/cpu.rs` to provide the -following exit calls for the kernel: - -```rust -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- -use qemu_exit::QEMUExit; - -const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); - -/// Make the host QEMU binary execute `exit(1)`. -pub fn qemu_exit_failure() -> ! { - QEMU_EXIT_HANDLE.exit_failure() -} - -/// Make the host QEMU binary execute `exit(0)`. -pub fn qemu_exit_success() -> ! { - QEMU_EXIT_HANDLE.exit_success() -} -``` - -[Click here] in case you are interested in the implementation. Note that for the functions to work, -the `-semihosting` flag must be added to the `QEMU` invocation. - -[exit status]: https://en.wikipedia.org/wiki/Exit_status -[@phil-opp]: https://github.com/phil-opp -[learned how to do this]: https://os.phil-opp.com/testing/#exiting-qemu -[semihosting]: https://static.docs.arm.com/100863/0200/semihosting.pdf -[qemu-exit]: https://github.com/andre-richter/qemu-exit -[Click here]: https://github.com/andre-richter/qemu-exit/blob/master/src/aarch64.rs - -#### Exiting Unit Tests - -Unit test failure shall be triggered by the `panic!` macro, either directly or by way of using -`assert!` macros. Until now, our `panic!` implementation finally called `cpu::wait_forever()` to -safely park the panicked CPU core in a busy loop. This can't be used for the unit tests, because -`cargo` would wait forever for `QEMU` to exit and stall the whole test run. Again, conditional -compilation is used to differentiate between a release and testing version of how a `panic!` -concludes. Here is the new testing version: - -```rust -/// The point of exit when the library is compiled for testing. -#[cfg(test)] -#[no_mangle] -fn _panic_exit() -> ! { - cpu::qemu_exit_failure() -} -``` - -In case none of the unit tests panicked, `lib.rs`'s `kernel_init()` calls -`cpu::qemu_exit_success()` to successfully conclude the unit test run. - -### Controlling Test Kernel Execution - -Now is a good time to catch up on how the test kernel binary is actually being executed. Normally, -`cargo test` would try to execute the compiled binary as a normal child process. This would fail -horribly because we build a kernel, and not a userspace process. Also, chances are very high that -you sit in front of an `x86` machine, whereas the RPi kernel is `AArch64`. - -Therefore, we need to install some hooks that make sure the test kernel gets executed inside `QEMU`, -quite like it is done for the existing `make qemu` target that is in place since tutorial 1. The -first step is to add a new file to the project, `.cargo/config.toml`: - -```toml -[target.'cfg(target_os = "none")'] -runner = "target/kernel_test_runner.sh" -``` - -Instead of executing a compilation result directly, the `runner` flag will instruct `cargo` to -delegate the execution. Using the setting depicted above, `target/kernel_test_runner.sh` will be -executed and given the full path to the compiled test kernel as the first command line argument. - -The file `kernel_test_runner.sh` does not exist by default. We generate it on demand throguh the -`make test` target: - -```Makefile -define KERNEL_TEST_RUNNER - #!/usr/bin/env bash - - $(OBJCOPY_CMD) $$1 $$1.img - TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') - $(DOCKER_TEST) ruby tests/runner.rb $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY -endef - -export KERNEL_TEST_RUNNER -test: - @mkdir -p target - @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh - @chmod +x target/kernel_test_runner.sh - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) -``` - -It first does the standard `objcopy` step to strip the `ELF` down to a raw binary. Just like in all -the other Makefile targets. Next, the script generates a relative path from the absolute path -provided to it by `cargo`, and finally compiles a `docker` command to execute the test kernel. For -reference, here it is fully resolved for an `RPi3 BSP`: - -```bash -docker run -i --rm -v /opt/rust-raspberrypi-OS-tutorials/13_integrated_testing:/work/tutorial -w /work/tutorial rustembedded/osdev-utils ruby tests/runner.rb qemu-system-aarch64 -M raspi3 -serial stdio -display none -semihosting -kernel $TEST_BINARY -``` - -We're still not done with all the redirections. Spotted the `ruby tests/runner.rb` part that gets -excuted inside Docker? - -#### Wrapping QEMU Test Execution - -`runner.rb` is a [Ruby] wrapper script around `QEMU` that, for unit tests, catches the case that a -test gets stuck, e.g. in an unintentional busy loop or a crash. If `runner.rb` does not observe any -output of the test kernel for `5 seconds`, it cancels the execution and reports a failure back to -`cargo`. If `QEMU` exited itself by means of `aarch64::exit_success() / aarch64::exit_failure()`, -the respective exit status code is passed through. The essential part happens here in `class -RawTest`: - -```ruby -def exec - error = 'Timed out waiting for test' - io = IO.popen(@qemu_cmd) - - while IO.select([io], nil, nil, MAX_WAIT_SECS) - begin - @output << io.read_nonblock(1024) - rescue EOFError - io.close - error = $CHILD_STATUS.to_i != 0 - break - end - end -``` - -[Ruby]: https://www.ruby-lang.org/ - -### Writing Unit Tests - -Alright, that's a wrap for the whole chain from `make test` all the way to reporting the test exit -status back to `cargo test`. It is a lot to digest already, but we haven't even learned to write -`Unit Tests` yet. - -In essence, it is almost like in `std` environments, with the difference that `#[test]` can't be -used, because it is part of the standard library. The `no_std` replacement attribute provided by -`custom_test_frameworks` is `#[test_case]`. You can put `#[test_case]` before functions, constants -or statics (you have to decide for one and stick with it). Each attributed item is added to the -"list" that is then passed to the `test_runner` function. - -As you learned earlier, we decided that our tests shall be instances of `test_types::UnitTest`. Here -is the type definition again: - -```rust -/// Unit test container. -pub struct UnitTest { - /// Name of the test. - pub name: &'static str, - - /// Function pointer to the test. - pub test_func: fn(), -} -``` - -So what we could do now is write something like: - -```rust -#[cfg(test)] -mod tests { - use super::*; - - #[test_case] - const TEST1: test_types::UnitTest = test_types::UnitTest { - name: "test_runner_executes_in_kernel_mode", - test_func: || { - let (level, _) = current_privilege_level(); - - assert!(level == PrivilegeLevel::Kernel) - }, - }; -} -``` - -Since this is a bit boiler-platy with the const and name definition, let's write a [procedural -macro] named `#[kernel_test]` to simplify this. It should work this way: - - 1. Must be put before functions that take no arguments and return nothing. - 2. Automatically constructs a `const UnitTest` from attributed functions like shown above by: - 1. Converting the function name to the `name` member of the `UnitTest` struct. - 2. Populating the `test_func` member with a closure that executes the body of the attributed - function. - -For the sake of brevity, we're not going to discuss the macro implementation. [The source is in the -test-macros crate] if you're interested in it. Using the macro, the example shown before now boils -down to this (this is now an actual example from [exception.rs]: - -[procedural macro]: https://doc.rust-lang.org/reference/procedural-macros.html -[The source is in the test-macros crate]: test-macros/src/lib.rs -[exception.rs]: src/exception.rs - -```rust -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Libkernel unit tests must execute in kernel mode. - #[kernel_test] - fn test_runner_executes_in_kernel_mode() { - let (level, _) = current_privilege_level(); - - assert!(level == PrivilegeLevel::Kernel) - } -} -``` - -Note that since proc macros need to live in their own crates, we need to create a new one at -`$ROOT/test-macros` and save it there. - -Aaaaaand that's how you write unit tests. We're finished with that part for good now :raised_hands:. - -### Integration Tests - -We are still not done with the tutorial, though :scream:. - -Integration tests need some special attention here and there too. As you already learned, they live -in `$CRATE/tests/`. Each `.rs` file in there gets compiled into its own test kernel binary and -executed separately by `cargo test`. The code in the integration tests includes the library part of -our kernel (`libkernel`) through `use` statements. - -Also note that the entry point for each `integration test` must be the `kernel_init()` function -again, just like in the `unit test` case. - -#### Test Harness - -By default, `cargo test` will pull in the test harness (that's the official name for the generated -`main()` function) into integration tests as well. This gives you a further means of partitioning -your test code into individual chunks. For example, take a look at `tests/01_timer_sanity.rs`: - -```rust -//! Timer sanity tests. - -#![feature(custom_test_frameworks)] -#![no_main] -#![no_std] -#![reexport_test_harness_main = "test_main"] -#![test_runner(libkernel::test_runner)] - -mod panic_exit_failure; - -use core::time::Duration; -use libkernel::{bsp, cpu, time, time::interface::TimeManager}; -use test_macros::kernel_test; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. - - test_main(); - - cpu::qemu_exit_success() -} - -/// Simple check that the timer is running. -#[kernel_test] -fn timer_is_counting() { - assert!(time::time_manager().uptime().as_nanos() > 0) -} - -/// Timer resolution must be sufficient. -#[kernel_test] -fn timer_resolution_is_sufficient() { - assert!(time::time_manager().resolution().as_nanos() < 100) -} -``` - -Note how the `test_runner` from `libkernel` is pulled in through -`#![test_runner(libkernel::test_runner)]`. - -#### No Test Harness - -For some tests, however, it is not needed to have the harness, because there is no need or -possibility to partition the test into individual pieces. In this case, all the test code can live -in `kernel_init()`, and harness generation can be turned off through `Cargo.toml`. This tutorial -introduces two tests that don't need a harness. Here is how harness generation is turned off for -them: - -```toml -# List of tests without harness. -[[test]] -name = "00_console_sanity" -harness = false - -[[test]] -name = "02_exception_sync_page_fault" -harness = false -``` - -#### Overriding Panic Behavior - -It is also important to understand that the `libkernel` made available to the integration tests is -the _release_ version. Therefore, it won't contain any code attributed with `#[cfg(test)]`! - -One of the implications of this is that the `panic handler` provided by `libkernel` will be the -version from the release kernel that spins forever, and not the test version that exits `QEMU`. - -One way to navigate around this is to declare the _release version of the panic exit function_ in -`lib.rs` as a [weak symbol]: - -```rust -#[cfg(not(test))] -#[linkage = "weak"] -#[no_mangle] -fn _panic_exit() -> ! { - cpu::wait_forever() -} -``` - -[weak symbol]: https://en.wikipedia.org/wiki/Weak_symbol - -Integration tests in `$CRATE/tests/` can now override it according to their needs, because depending -on the kind of test, a `panic!` could mean success or failure. For example, -`tests/02_exception_sync_page_fault.rs` is intentionally causing a page fault, so the wanted outcome -is a `panic!`. Here is the whole test (minus some inline comments): - -```rust -//! Page faults must result in synchronous exceptions. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -mod panic_exit_success; - -use libkernel::{bsp, cpu, exception, memory, println}; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - use memory::mmu::interface::MMU; - - bsp::console::qemu_bring_up_console(); - - println!("Testing synchronous exception handling by causing a page fault"); - println!("-------------------------------------------------------------------\n"); - - exception::handling_init(); - - if let Err(string) = memory::mmu::mmu().init() { - println!("MMU: {}", string); - cpu::qemu_exit_failure() - } - - println!("Writing beyond mapped area to address 9 GiB..."); - let big_addr: u64 = 9 * 1024 * 1024 * 1024; - core::ptr::read_volatile(big_addr as *mut u64); - - // If execution reaches here, the memory access above did not cause a page fault exception. - cpu::qemu_exit_failure() -} -``` - -The `_panic_exit()` version that makes `QEMU` return `0` (indicating test success) is pulled in by -`mod panic_exit_success;`. The counterpart would be `mod panic_exit_failure;`. We provide both in -the `tests` folder, so each integration test can import the one that it needs. - -### Console Tests - -As the kernel or OS grows, it will be more and more interesting to test user/kernel interaction -through the serial console. That is, sending strings/characters to the console and expecting -specific answers in return. The `runner.rb` wrapper script provides infrastructure to do this with -little overhead. It basically works like this: - - 1. For each integration test, check if a companion file to the `.rs` test file exists. - - A companion file has the same name, but ends in `.rb`. - - The companion file contains one or more console subtests. - 2. If it exists, load the file to dynamically import the console subtests. - 3. Spawn `QEMU` and attach to the serial console. - 4. Run the console subtests. - -Here is an excerpt from `00_console_sanity.rb` showing a subtest that does a handshake with the -kernel over the console: - -```ruby -TIMEOUT_SECS = 3 - -# Verify sending and receiving works as expected. -class TxRxHandshake - def name - 'Transmit and Receive handshake' - end - - def run(qemu_out, qemu_in) - qemu_in.write_nonblock('ABC') - raise('TX/RX test failed') if qemu_out.expect('OK1234', TIMEOUT_SECS).nil? - end -end -``` - -The subtest first sends `"ABC"` over the console to the kernel, and then expects to receive -`"OK1234"` back. On the kernel side, it looks like this in `00_console_sanity.rs`: - -```rust -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -mod panic_exit_failure; - -use libkernel::{bsp, console, print}; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - use bsp::console::{console, qemu_bring_up_console}; - use console::interface::*; - - qemu_bring_up_console(); - - // Handshake - assert_eq!(console().read_char(), 'A'); - assert_eq!(console().read_char(), 'B'); - assert_eq!(console().read_char(), 'C'); - print!("OK1234"); -``` - -## Test it - -Believe it or not, that is all. There are three ways you can run tests: - - 1. `make test` will run all tests back-to-back. - 2. `TEST=unit make test` will run `libkernel`'s unit tests. - 3. `TEST=TEST_NAME make test` will run a specficic integration test. - - For example, `TEST=01_timer_sanity make test` - -```console -$ make test -[...] -RUSTFLAGS="-C link-arg=-Tsrc/bsp/raspberrypi/link.ld -C target-cpu=cortex-a53 -D warnings -D missing_docs" cargo test --target=aarch64-unknown-none-softfloat --features bsp_rpi3 --release - Finished release [optimized] target(s) in 0.01s - Running target/aarch64-unknown-none-softfloat/release/deps/libkernel-4cc6412ddf631982 - ------------------------------------------------------------------- - 🦀 Running 8 tests - ------------------------------------------------------------------- - - 1. virt_mem_layout_sections_are_64KiB_aligned................[ok] - 2. virt_mem_layout_has_no_overlaps...........................[ok] - 3. test_runner_executes_in_kernel_mode.......................[ok] - 4. size_of_tabledescriptor_equals_64_bit.....................[ok] - 5. size_of_pagedescriptor_equals_64_bit......................[ok] - 6. kernel_tables_in_bss......................................[ok] - 7. zero_volatile_works.......................................[ok] - 8. bss_section_is_sane.......................................[ok] - - ------------------------------------------------------------------- - ✅ Success: libkernel - ------------------------------------------------------------------- - - - Running target/aarch64-unknown-none-softfloat/release/deps/00_console_sanity-557819b436f15a18 - ------------------------------------------------------------------- - 🦀 Running 3 console-based tests - ------------------------------------------------------------------- - - 1. Transmit and Receive handshake............................[ok] - 2. Transmit statistics.......................................[ok] - 3. Receive statistics........................................[ok] - - ------------------------------------------------------------------- - ✅ Success: 00_console_sanity - ------------------------------------------------------------------- - - - Running target/aarch64-unknown-none-softfloat/release/deps/01_timer_sanity-1e25e7d559a9009f - ------------------------------------------------------------------- - 🦀 Running 3 tests - ------------------------------------------------------------------- - - 1. timer_is_counting.........................................[ok] - 2. timer_resolution_is_sufficient............................[ok] - 3. spin_accuracy_check_1_second..............................[ok] - - ------------------------------------------------------------------- - ✅ Success: 01_timer_sanity - ------------------------------------------------------------------- - - - Running target/aarch64-unknown-none-softfloat/release/deps/02_exception_sync_page_fault-14172ce39b3fae1c - ------------------------------------------------------------------- - 🦀 Testing synchronous exception handling by causing a page fault - ------------------------------------------------------------------- - - Writing beyond mapped area to address 9 GiB... - - Kernel panic: - - CPU Exception! - FAR_EL1: 0x0000000240000000 - ESR_EL1: 0x96000004 - [...] - - ------------------------------------------------------------------- - ✅ Success: 02_exception_sync_page_fault - ------------------------------------------------------------------- -``` - -## Diff to previous -```diff - -diff -uNr 12_exceptions_part1_groundwork/.cargo/config.toml 13_integrated_testing/.cargo/config.toml ---- 12_exceptions_part1_groundwork/.cargo/config.toml -+++ 13_integrated_testing/.cargo/config.toml -@@ -0,0 +1,2 @@ -+[target.'cfg(target_os = "none")'] -+runner = "target/kernel_test_runner.sh" - -diff -uNr 12_exceptions_part1_groundwork/Cargo.toml 13_integrated_testing/Cargo.toml ---- 12_exceptions_part1_groundwork/Cargo.toml -+++ 13_integrated_testing/Cargo.toml -@@ -18,11 +18,38 @@ - ##-------------------------------------------------------------------------------------------------- - - [dependencies] -+qemu-exit = "1.x.x" -+test-types = { path = "test-types" } - - # Optional dependencies --register = { version = "1.x.x", optional = true } -+register = { version = "1.x.x", features = ["no_std_unit_tests"], optional = true } - - # Platform specific dependencies - [target.'cfg(target_arch = "aarch64")'.dependencies] - cortex-a = { version = "5.x.x" } - -+##-------------------------------------------------------------------------------------------------- -+## Testing -+##-------------------------------------------------------------------------------------------------- -+ -+[dev-dependencies] -+test-macros = { path = "test-macros" } -+ -+# Unit tests are done in the library part of the kernel. -+[lib] -+name = "libkernel" -+test = true -+ -+# Disable unit tests for the kernel binary. -+[[bin]] -+name = "kernel" -+test = false -+ -+# List of tests without harness. -+[[test]] -+name = "00_console_sanity" -+harness = false -+ -+[[test]] -+name = "02_exception_sync_page_fault" -+harness = false - -diff -uNr 12_exceptions_part1_groundwork/Makefile 13_integrated_testing/Makefile ---- 12_exceptions_part1_groundwork/Makefile -+++ 13_integrated_testing/Makefile -@@ -18,6 +18,7 @@ - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none -+ QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg -@@ -30,6 +31,7 @@ - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none -+ QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg -@@ -41,6 +43,17 @@ - # Export for build.rs - export LINKER_FILE - -+# Testing-specific arguments -+ifdef TEST -+ ifeq ($(TEST),unit) -+ TEST_ARG = --lib -+ else -+ TEST_ARG = --test $(TEST) -+ endif -+endif -+ -+QEMU_MISSING_STRING = "This board is not yet supported for QEMU." -+ - RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) - RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -@@ -52,6 +65,7 @@ - DOC_CMD = cargo doc $(COMPILER_ARGS) - CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) - CHECK_CMD = cargo check $(COMPILER_ARGS) -+TEST_CMD = cargo test $(COMPILER_ARGS) - OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary -@@ -68,6 +82,7 @@ - - DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) - DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -+DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_IMAGE) - DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - - # Dockerize commands that require USB device passthrough only on Linux -@@ -84,8 +99,8 @@ - EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) - EXEC_MINIPUSH = ruby ../utils/minipush.rb - --.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot jtagboot openocd gdb gdb-opt0 clippy \ -- clean readelf objdump nm check -+.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu test chainboot jtagboot openocd gdb gdb-opt0 \ -+ clippy clean readelf objdump nm check - - all: $(KERNEL_BIN) - -@@ -99,11 +114,26 @@ - $(DOC_CMD) --document-private-items --open - - ifeq ($(QEMU_MACHINE_TYPE),) --qemu: -- @echo "This board is not yet supported for QEMU." -+qemu test: -+ @echo $(QEMU_MISSING_STRING) - else - qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -+ -+define KERNEL_TEST_RUNNER -+ #!/usr/bin/env bash -+ -+ $(OBJCOPY_CMD) $$1 $$1.img -+ TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') -+ $(DOCKER_TEST) ruby tests/runner.rb $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY -+endef -+ -+export KERNEL_TEST_RUNNER -+test: -+ @mkdir -p target -+ @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh -+ @chmod +x target/kernel_test_runner.sh -+ RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) - endif - - chainboot: $(KERNEL_BIN) - -diff -uNr 12_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs 13_integrated_testing/src/_arch/aarch64/cpu.rs ---- 12_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs -+++ 13_integrated_testing/src/_arch/aarch64/cpu.rs -@@ -87,3 +87,20 @@ - asm::wfe() - } - } -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+use qemu_exit::QEMUExit; -+ -+const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); -+ -+/// Make the host QEMU binary execute `exit(1)`. -+pub fn qemu_exit_failure() -> ! { -+ QEMU_EXIT_HANDLE.exit_failure() -+} -+ -+/// Make the host QEMU binary execute `exit(0)`. -+pub fn qemu_exit_success() -> ! { -+ QEMU_EXIT_HANDLE.exit_success() -+} - -diff -uNr 12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs 13_integrated_testing/src/_arch/aarch64/exception.rs ---- 12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs -+++ 13_integrated_testing/src/_arch/aarch64/exception.rs -@@ -5,7 +5,7 @@ - //! Architectural synchronous and asynchronous exception handling. - - use core::{cell::UnsafeCell, fmt}; --use cortex_a::{asm, barrier, regs::*}; -+use cortex_a::{barrier, regs::*}; - use register::InMemoryRegister; - - // Assembly counterpart to this file. -@@ -80,16 +80,6 @@ - - #[no_mangle] - unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { -- let far_el1 = FAR_EL1.get(); -- -- // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, -- // advance the exception link register for one instruction, so that execution can continue. -- if far_el1 == 8 * 1024 * 1024 * 1024 { -- e.elr_el1 += 4; -- -- asm::eret() -- } -- - default_exception_handler(e); - } - - -diff -uNr 12_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs 13_integrated_testing/src/_arch/aarch64/memory/mmu.rs ---- 12_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs -+++ 13_integrated_testing/src/_arch/aarch64/memory/mmu.rs -@@ -331,3 +331,40 @@ - Ok(()) - } - } -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ use test_macros::kernel_test; -+ -+ /// Check if the size of `struct TableDescriptor` is as expected. -+ #[kernel_test] -+ fn size_of_tabledescriptor_equals_64_bit() { -+ assert_eq!( -+ core::mem::size_of::(), -+ core::mem::size_of::() -+ ); -+ } -+ -+ /// Check if the size of `struct PageDescriptor` is as expected. -+ #[kernel_test] -+ fn size_of_pagedescriptor_equals_64_bit() { -+ assert_eq!( -+ core::mem::size_of::(), -+ core::mem::size_of::() -+ ); -+ } -+ -+ /// Check if KERNEL_TABLES is in .bss. -+ #[kernel_test] -+ fn kernel_tables_in_bss() { -+ let bss_range = bsp::memory::bss_range_inclusive(); -+ let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; -+ -+ assert!(bss_range.contains(&kernel_tables_addr)); -+ } -+} - -diff -uNr 12_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs 13_integrated_testing/src/bsp/raspberrypi/console.rs ---- 12_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs -+++ 13_integrated_testing/src/bsp/raspberrypi/console.rs -@@ -35,3 +35,13 @@ - pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART - } -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+ -+/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps -+/// than on real hardware due to QEMU's abstractions. -+/// -+/// For the RPi, nothing needs to be done. -+pub fn qemu_bring_up_console() {} - -diff -uNr 12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs 13_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs ---- 12_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs -+++ 13_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs -@@ -71,3 +71,46 @@ - pub fn virt_mem_layout() -> &'static KernelVirtualLayout<{ NUM_MEM_RANGES }> { - &LAYOUT - } -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ use test_macros::kernel_test; -+ -+ /// Check alignment of the kernel's virtual memory layout sections. -+ #[kernel_test] -+ fn virt_mem_layout_sections_are_64KiB_aligned() { -+ const SIXTYFOUR_KIB: usize = 65536; -+ -+ for i in LAYOUT.inner().iter() { -+ let start: usize = *(i.virtual_range)().start(); -+ let end: usize = *(i.virtual_range)().end() + 1; -+ -+ assert_eq!(start modulo SIXTYFOUR_KIB, 0); -+ assert_eq!(end modulo SIXTYFOUR_KIB, 0); -+ assert!(end >= start); -+ } -+ } -+ -+ /// Ensure the kernel's virtual memory layout is free of overlaps. -+ #[kernel_test] -+ fn virt_mem_layout_has_no_overlaps() { -+ let layout = virt_mem_layout().inner(); -+ -+ for (i, first) in layout.iter().enumerate() { -+ for second in layout.iter().skip(i + 1) { -+ let first_range = first.virtual_range; -+ let second_range = second.virtual_range; -+ -+ assert!(!first_range().contains(second_range().start())); -+ assert!(!first_range().contains(second_range().end())); -+ assert!(!second_range().contains(first_range().start())); -+ assert!(!second_range().contains(first_range().end())); -+ } -+ } -+ } -+} - -diff -uNr 12_exceptions_part1_groundwork/src/exception.rs 13_integrated_testing/src/exception.rs ---- 12_exceptions_part1_groundwork/src/exception.rs -+++ 13_integrated_testing/src/exception.rs -@@ -24,3 +24,21 @@ - Hypervisor, - Unknown, - } -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ use test_macros::kernel_test; -+ -+ /// Libkernel unit tests must execute in kernel mode. -+ #[kernel_test] -+ fn test_runner_executes_in_kernel_mode() { -+ let (level, _) = current_privilege_level(); -+ -+ assert!(level == PrivilegeLevel::Kernel) -+ } -+} - -diff -uNr 12_exceptions_part1_groundwork/src/lib.rs 13_integrated_testing/src/lib.rs ---- 12_exceptions_part1_groundwork/src/lib.rs -+++ 13_integrated_testing/src/lib.rs -@@ -0,0 +1,170 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2020 Andre Richter -+ -+// Rust embedded logo for `make doc`. -+#![doc(html_logo_url = "https://git.io/JeGIp")] -+ -+//! The `kernel` library. -+//! -+//! Used by `main.rs` to compose the final kernel binary. -+//! -+//! # TL;DR - Overview of important Kernel entities -+//! -+//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -+//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -+//! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. -+//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -+//! -+//! [console interface]: ../libkernel/console/interface/index.html -+//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -+//! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html -+//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -+//! -+//! # Code organization and architecture -+//! -+//! The code is divided into different *modules*, each representing a typical **subsystem** of the -+//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -+//! `src/memory.rs` contains code that is concerned with all things memory management. -+//! -+//! ## Visibility of processor architecture code -+//! -+//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -+//! processor architecture. For each supported processor architecture, there exists a subfolder in -+//! `src/_arch`, for example, `src/_arch/aarch64`. -+//! -+//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -+//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -+//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -+//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -+//! module organization. That means a public function `foo()` defined in -+//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -+//! -+//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -+//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -+//! "_arch/xxx/yyy.rs"]` attribute. -+//! -+//! ## BSP code -+//! -+//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -+//! target board specific definitions and functions. These are things such as the board's memory map -+//! or instances of drivers for devices that are featured on the respective board. -+//! -+//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -+//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -+//! whatever is provided must be called starting from the `bsp` namespace, e.g. -+//! `bsp::driver::driver_manager()`. -+//! -+//! ## Kernel interfaces -+//! -+//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -+//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -+//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -+//! code to play nicely with any of the two without much hassle. -+//! -+//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -+//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -+//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -+//! not an implementation*. For example, there will be a common IRQ handling interface which the two -+//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -+//! interface to the rest of the `kernel`. -+//! -+//! ``` -+//! +-------------------+ -+//! | Interface (Trait) | -+//! | | -+//! +--+-------------+--+ -+//! ^ ^ -+//! | | -+//! | | -+//! +----------+--+ +--+----------+ -+//! | kernel code | | bsp code | -+//! | | | arch code | -+//! +-------------+ +-------------+ -+//! ``` -+//! -+//! # Summary -+//! -+//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -+//! locations. Here is an example for the **memory** subsystem: -+//! -+//! - `src/memory.rs` and `src/memory/**/*` -+//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -+//! - Example: A function to zero a chunk of memory. -+//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -+//! - Example: An `MMU` interface that defines `MMU` function prototypes. -+//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -+//! - `BSP` specific code. -+//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -+//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -+//! - Processor architecture specific code. -+//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -+//! architecture. -+//! -+//! From a namespace perspective, **memory** subsystem code lives in: -+//! -+//! - `crate::memory::*` -+//! - `crate::bsp::memory::*` -+ -+#![allow(incomplete_features)] -+#![feature(const_fn_fn_ptr_basics)] -+#![feature(const_generics)] -+#![feature(const_panic)] -+#![feature(format_args_nl)] -+#![feature(global_asm)] -+#![feature(linkage)] -+#![feature(naked_functions)] -+#![feature(panic_info_message)] -+#![feature(trait_alias)] -+#![no_std] -+// Testing -+#![cfg_attr(test, no_main)] -+#![feature(custom_test_frameworks)] -+#![reexport_test_harness_main = "test_main"] -+#![test_runner(crate::test_runner)] -+ -+// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -+// `runtime_init()`, which jumps to `kernel_init()` (defined in `main.rs`). -+ -+mod panic_wait; -+mod runtime_init; -+mod synchronization; -+ -+pub mod bsp; -+pub mod console; -+pub mod cpu; -+pub mod driver; -+pub mod exception; -+pub mod memory; -+pub mod print; -+pub mod time; -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+ -+/// The default runner for unit tests. -+pub fn test_runner(tests: &[&test_types::UnitTest]) { -+ println!("Running {} tests", tests.len()); -+ println!("-------------------------------------------------------------------\n"); -+ for (i, test) in tests.iter().enumerate() { -+ print!("{:>3}. {:.<58}", i + 1, test.name); -+ -+ // Run the actual test. -+ (test.test_func)(); -+ -+ // Failed tests call panic!(). Execution reaches here only if the test has passed. -+ println!("[ok]") -+ } -+} -+ -+/// The `kernel_init()` for unit tests. Called from `runtime_init()`. -+#[cfg(test)] -+#[no_mangle] -+unsafe fn kernel_init() -> ! { -+ bsp::console::qemu_bring_up_console(); -+ -+ test_main(); -+ -+ cpu::qemu_exit_success() -+} - -diff -uNr 12_exceptions_part1_groundwork/src/main.rs 13_integrated_testing/src/main.rs ---- 12_exceptions_part1_groundwork/src/main.rs -+++ 13_integrated_testing/src/main.rs -@@ -6,130 +6,12 @@ - #![doc(html_logo_url = "https://git.io/JeGIp")] - - //! The `kernel` binary. --//! --//! # TL;DR - Overview of important Kernel entities --//! --//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. --//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. --//! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. --//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. --//! --//! [console interface]: ../libkernel/console/interface/index.html --//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html --//! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html --//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html --//! --//! # Code organization and architecture --//! --//! The code is divided into different *modules*, each representing a typical **subsystem** of the --//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, --//! `src/memory.rs` contains code that is concerned with all things memory management. --//! --//! ## Visibility of processor architecture code --//! --//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target --//! processor architecture. For each supported processor architecture, there exists a subfolder in --//! `src/_arch`, for example, `src/_arch/aarch64`. --//! --//! The architecture folders mirror the subsystem modules laid out in `src`. For example, --//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go --//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in --//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's --//! module organization. That means a public function `foo()` defined in --//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. --//! --//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. --//! Rather, it's contents are conditionally pulled into respective files using the `#[path = --//! "_arch/xxx/yyy.rs"]` attribute. --//! --//! ## BSP code --//! --//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains --//! target board specific definitions and functions. These are things such as the board's memory map --//! or instances of drivers for devices that are featured on the respective board. --//! --//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the --//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means --//! whatever is provided must be called starting from the `bsp` namespace, e.g. --//! `bsp::driver::driver_manager()`. --//! --//! ## Kernel interfaces --//! --//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target --//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of --//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` --//! code to play nicely with any of the two without much hassle. --//! --//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, --//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined --//! in the respective subsystem module and help to enforce the idiom of *program to an interface, --//! not an implementation*. For example, there will be a common IRQ handling interface which the two --//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the --//! interface to the rest of the `kernel`. --//! --//! ``` --//! +-------------------+ --//! | Interface (Trait) | --//! | | --//! +--+-------------+--+ --//! ^ ^ --//! | | --//! | | --//! +----------+--+ +--+----------+ --//! | kernel code | | bsp code | --//! | | | arch code | --//! +-------------+ +-------------+ --//! ``` --//! --//! # Summary --//! --//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical --//! locations. Here is an example for the **memory** subsystem: --//! --//! - `src/memory.rs` and `src/memory/**/*` --//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. --//! - Example: A function to zero a chunk of memory. --//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. --//! - Example: An `MMU` interface that defines `MMU` function prototypes. --//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` --//! - `BSP` specific code. --//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). --//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` --//! - Processor architecture specific code. --//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor --//! architecture. --//! --//! From a namespace perspective, **memory** subsystem code lives in: --//! --//! - `crate::memory::*` --//! - `crate::bsp::memory::*` -- --#![allow(incomplete_features)] --#![feature(const_fn_fn_ptr_basics)] --#![feature(const_generics)] --#![feature(const_panic)] -+ - #![feature(format_args_nl)] --#![feature(global_asm)] --#![feature(naked_functions)] --#![feature(panic_info_message)] --#![feature(trait_alias)] - #![no_main] - #![no_std] - --// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls --// `runtime_init()`, which jumps to `kernel_init()`. -- --mod bsp; --mod console; --mod cpu; --mod driver; --mod exception; --mod memory; --mod panic_wait; --mod print; --mod runtime_init; --mod synchronization; --mod time; -+use libkernel::{bsp, console, driver, exception, info, memory, time}; - - /// Early init code. - /// -@@ -141,6 +23,7 @@ - /// - Without it, any atomic operations, e.g. the yet-to-be-introduced spinlocks in the device - /// drivers (which currently employ NullLocks instead of spinlocks), will fail to work on - /// the RPi SoCs. -+#[no_mangle] - unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - use memory::mmu::interface::MMU; -@@ -166,9 +49,7 @@ - /// The main function running after the early init. - fn kernel_main() -> ! { - use console::interface::All; -- use core::time::Duration; - use driver::interface::DriverManager; -- use time::interface::TimeManager; - - info!("Booting on: {}", bsp::board_name()); - -@@ -195,31 +76,6 @@ - info!(" {}. {}", i + 1, driver.compatible()); - } - -- info!("Timer test, spinning for 1 second"); -- time::time_manager().spin_for(Duration::from_secs(1)); -- -- // Cause an exception by accessing a virtual address for which no translation was set up. This -- // code accesses the address 8 GiB, which is outside the mapped address space. -- // -- // For demo purposes, the exception handler will catch the faulting 8 GiB address and allow -- // execution to continue. -- info!(""); -- info!("Trying to write to address 8 GiB..."); -- let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; -- unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; -- -- info!("************************************************"); -- info!("Whoa! We recovered from a synchronous exception!"); -- info!("************************************************"); -- info!(""); -- info!("Let's try again"); -- -- // Now use address 9 GiB. The exception handler won't forgive us this time. -- info!("Trying to write to address 9 GiB..."); -- big_addr = 9 * 1024 * 1024 * 1024; -- unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; -- -- // Will never reach here in this tutorial. - info!("Echoing input now"); - loop { - let c = bsp::console::console().read_char(); - -diff -uNr 12_exceptions_part1_groundwork/src/memory/mmu.rs 13_integrated_testing/src/memory/mmu.rs ---- 12_exceptions_part1_groundwork/src/memory/mmu.rs -+++ 13_integrated_testing/src/memory/mmu.rs -@@ -42,7 +42,6 @@ - - /// Architecture agnostic translation types. - #[allow(missing_docs)] --#[allow(dead_code)] - #[derive(Copy, Clone)] - pub enum Translation { - Identity, -@@ -197,4 +196,9 @@ - info!("{}", i); - } - } -+ -+ #[cfg(test)] -+ pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { -+ &self.inner -+ } - } - -diff -uNr 12_exceptions_part1_groundwork/src/memory.rs 13_integrated_testing/src/memory.rs ---- 12_exceptions_part1_groundwork/src/memory.rs -+++ 13_integrated_testing/src/memory.rs -@@ -30,3 +30,40 @@ - ptr = ptr.offset(1); - } - } -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ use test_macros::kernel_test; -+ -+ /// Check `zero_volatile()`. -+ #[kernel_test] -+ fn zero_volatile_works() { -+ let mut x: [usize; 3] = [10, 11, 12]; -+ let x_range = x.as_mut_ptr_range(); -+ let x_range_inclusive = -+ RangeInclusive::new(x_range.start, unsafe { x_range.end.offset(-1) }); -+ -+ unsafe { zero_volatile(x_range_inclusive) }; -+ -+ assert_eq!(x, [0, 0, 0]); -+ } -+ -+ /// Check `bss` section layout. -+ #[kernel_test] -+ fn bss_section_is_sane() { -+ use crate::bsp::memory::bss_range_inclusive; -+ use core::mem; -+ -+ let start = *bss_range_inclusive().start() as usize; -+ let end = *bss_range_inclusive().end() as usize; -+ -+ assert_eq!(start modulo mem::size_of::(), 0); -+ assert_eq!(end modulo mem::size_of::(), 0); -+ assert!(end >= start); -+ } -+} - -diff -uNr 12_exceptions_part1_groundwork/src/panic_wait.rs 13_integrated_testing/src/panic_wait.rs ---- 12_exceptions_part1_groundwork/src/panic_wait.rs -+++ 13_integrated_testing/src/panic_wait.rs -@@ -17,6 +17,23 @@ - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; - } - -+/// The point of exit for the "standard" (non-testing) `libkernel`. -+/// -+/// This code will be used by the release kernel binary and the `integration tests`. It is linked -+/// weakly, so that the integration tests can overload it to exit `QEMU` instead of spinning -+/// forever. -+/// -+/// This is one possible approach to solve the problem that `cargo` can not know who the consumer of -+/// the library will be: -+/// - The release kernel binary that should safely park the paniced core, -+/// - or an `integration test` that is executed in QEMU, which should just exit QEMU. -+#[cfg(not(test))] -+#[linkage = "weak"] -+#[no_mangle] -+fn _panic_exit() -> ! { -+ cpu::wait_forever() -+} -+ - /// Prints with a newline - only use from the panic handler. - /// - /// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -@@ -35,5 +52,16 @@ - panic_println!("\nKernel panic!"); - } - -- cpu::wait_forever() -+ _panic_exit() -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+ -+/// The point of exit when the library is compiled for testing. -+#[cfg(test)] -+#[no_mangle] -+fn _panic_exit() -> ! { -+ cpu::qemu_exit_failure() - } - -diff -uNr 12_exceptions_part1_groundwork/src/runtime_init.rs 13_integrated_testing/src/runtime_init.rs ---- 12_exceptions_part1_groundwork/src/runtime_init.rs -+++ 13_integrated_testing/src/runtime_init.rs -@@ -31,7 +31,10 @@ - /// - /// - Only a single core must be active and running this function. - pub unsafe fn runtime_init() -> ! { -- zero_bss(); -+ extern "Rust" { -+ fn kernel_init() -> !; -+ } - -- crate::kernel_init() -+ zero_bss(); -+ kernel_init() - } - -diff -uNr 12_exceptions_part1_groundwork/test-macros/Cargo.toml 13_integrated_testing/test-macros/Cargo.toml ---- 12_exceptions_part1_groundwork/test-macros/Cargo.toml -+++ 13_integrated_testing/test-macros/Cargo.toml -@@ -0,0 +1,14 @@ -+[package] -+name = "test-macros" -+version = "0.1.0" -+authors = ["Andre Richter "] -+edition = "2018" -+ -+[lib] -+proc-macro = true -+ -+[dependencies] -+proc-macro2 = "1.x" -+quote = "1.x" -+syn = { version = "1.x", features = ["full"] } -+test-types = { path = "../test-types" } - -diff -uNr 12_exceptions_part1_groundwork/test-macros/src/lib.rs 13_integrated_testing/test-macros/src/lib.rs ---- 12_exceptions_part1_groundwork/test-macros/src/lib.rs -+++ 13_integrated_testing/test-macros/src/lib.rs -@@ -0,0 +1,29 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2020 Andre Richter -+ -+use proc_macro::TokenStream; -+use proc_macro2::Span; -+use quote::quote; -+use syn::{parse_macro_input, Ident, ItemFn}; -+ -+#[proc_macro_attribute] -+pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { -+ let f = parse_macro_input!(input as ItemFn); -+ -+ let test_name = &format!("{}", f.sig.ident.to_string()); -+ let test_ident = Ident::new( -+ &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), -+ Span::call_site(), -+ ); -+ let test_code_block = f.block; -+ -+ quote!( -+ #[test_case] -+ const #test_ident: test_types::UnitTest = test_types::UnitTest { -+ name: #test_name, -+ test_func: || #test_code_block, -+ }; -+ ) -+ .into() -+} - -diff -uNr 12_exceptions_part1_groundwork/tests/00_console_sanity.rb 13_integrated_testing/tests/00_console_sanity.rb ---- 12_exceptions_part1_groundwork/tests/00_console_sanity.rb -+++ 13_integrated_testing/tests/00_console_sanity.rb -@@ -0,0 +1,50 @@ -+# frozen_string_literal: true -+ -+# SPDX-License-Identifier: MIT OR Apache-2.0 -+# -+# Copyright (c) 2019-2020 Andre Richter -+ -+require 'expect' -+ -+TIMEOUT_SECS = 3 -+ -+# Verify sending and receiving works as expected. -+class TxRxHandshake -+ def name -+ 'Transmit and Receive handshake' -+ end -+ -+ def run(qemu_out, qemu_in) -+ qemu_in.write_nonblock('ABC') -+ raise('TX/RX test failed') if qemu_out.expect('OK1234', TIMEOUT_SECS).nil? -+ end -+end -+ -+# Check for correct TX statistics implementation. Depends on test 1 being run first. -+class TxStatistics -+ def name -+ 'Transmit statistics' -+ end -+ -+ def run(qemu_out, _qemu_in) -+ raise('chars_written reported wrong') if qemu_out.expect('6', TIMEOUT_SECS).nil? -+ end -+end -+ -+# Check for correct RX statistics implementation. Depends on test 1 being run first. -+class RxStatistics -+ def name -+ 'Receive statistics' -+ end -+ -+ def run(qemu_out, _qemu_in) -+ raise('chars_read reported wrong') if qemu_out.expect('3', TIMEOUT_SECS).nil? -+ end -+end -+ -+##-------------------------------------------------------------------------------------------------- -+## Test registration -+##-------------------------------------------------------------------------------------------------- -+def subtest_collection -+ [TxRxHandshake.new, TxStatistics.new, RxStatistics.new] -+end - -diff -uNr 12_exceptions_part1_groundwork/tests/00_console_sanity.rs 13_integrated_testing/tests/00_console_sanity.rs ---- 12_exceptions_part1_groundwork/tests/00_console_sanity.rs -+++ 13_integrated_testing/tests/00_console_sanity.rs -@@ -0,0 +1,36 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2020 Andre Richter -+ -+//! Console sanity tests - RX, TX and statistics. -+ -+#![feature(format_args_nl)] -+#![no_main] -+#![no_std] -+ -+mod panic_exit_failure; -+ -+use libkernel::{bsp, console, print}; -+ -+#[no_mangle] -+unsafe fn kernel_init() -> ! { -+ use bsp::console::{console, qemu_bring_up_console}; -+ use console::interface::*; -+ -+ qemu_bring_up_console(); -+ -+ // Handshake -+ assert_eq!(console().read_char(), 'A'); -+ assert_eq!(console().read_char(), 'B'); -+ assert_eq!(console().read_char(), 'C'); -+ print!("OK1234"); -+ -+ // 6 -+ print!("{}", console().chars_written()); -+ -+ // 3 -+ print!("{}", console().chars_read()); -+ -+ // The QEMU process running this test will be closed by the I/O test harness. -+ loop {} -+} - -diff -uNr 12_exceptions_part1_groundwork/tests/01_timer_sanity.rs 13_integrated_testing/tests/01_timer_sanity.rs ---- 12_exceptions_part1_groundwork/tests/01_timer_sanity.rs -+++ 13_integrated_testing/tests/01_timer_sanity.rs -@@ -0,0 +1,50 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2020 Andre Richter -+ -+//! Timer sanity tests. -+ -+#![feature(custom_test_frameworks)] -+#![no_main] -+#![no_std] -+#![reexport_test_harness_main = "test_main"] -+#![test_runner(libkernel::test_runner)] -+ -+mod panic_exit_failure; -+ -+use core::time::Duration; -+use libkernel::{bsp, cpu, time, time::interface::TimeManager}; -+use test_macros::kernel_test; -+ -+#[no_mangle] -+unsafe fn kernel_init() -> ! { -+ bsp::console::qemu_bring_up_console(); -+ -+ // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. -+ -+ test_main(); -+ -+ cpu::qemu_exit_success() -+} -+ -+/// Simple check that the timer is running. -+#[kernel_test] -+fn timer_is_counting() { -+ assert!(time::time_manager().uptime().as_nanos() > 0) -+} -+ -+/// Timer resolution must be sufficient. -+#[kernel_test] -+fn timer_resolution_is_sufficient() { -+ assert!(time::time_manager().resolution().as_nanos() < 100) -+} -+ -+/// Sanity check spin_for() implementation. -+#[kernel_test] -+fn spin_accuracy_check_1_second() { -+ let t1 = time::time_manager().uptime(); -+ time::time_manager().spin_for(Duration::from_secs(1)); -+ let t2 = time::time_manager().uptime(); -+ -+ assert_eq!((t2 - t1).as_secs(), 1) -+} - -diff -uNr 12_exceptions_part1_groundwork/tests/02_exception_sync_page_fault.rs 13_integrated_testing/tests/02_exception_sync_page_fault.rs ---- 12_exceptions_part1_groundwork/tests/02_exception_sync_page_fault.rs -+++ 13_integrated_testing/tests/02_exception_sync_page_fault.rs -@@ -0,0 +1,44 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2020 Andre Richter -+ -+//! Page faults must result in synchronous exceptions. -+ -+#![feature(format_args_nl)] -+#![no_main] -+#![no_std] -+ -+/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -+/// -+/// Reaching this code is a success, because it is called from the synchronous exception handler, -+/// which is what this test wants to achieve. -+/// -+/// It also means that this integration test can not use any other code that calls panic!() directly -+/// or indirectly. -+mod panic_exit_success; -+ -+use libkernel::{bsp, cpu, exception, memory, println}; -+ -+#[no_mangle] -+unsafe fn kernel_init() -> ! { -+ use memory::mmu::interface::MMU; -+ -+ bsp::console::qemu_bring_up_console(); -+ -+ println!("Testing synchronous exception handling by causing a page fault"); -+ println!("-------------------------------------------------------------------\n"); -+ -+ exception::handling_init(); -+ -+ if let Err(string) = memory::mmu::mmu().init() { -+ println!("MMU: {}", string); -+ cpu::qemu_exit_failure() -+ } -+ -+ println!("Writing beyond mapped area to address 9 GiB..."); -+ let big_addr: u64 = 9 * 1024 * 1024 * 1024; -+ core::ptr::read_volatile(big_addr as *mut u64); -+ -+ // If execution reaches here, the memory access above did not cause a page fault exception. -+ cpu::qemu_exit_failure() -+} - -diff -uNr 12_exceptions_part1_groundwork/tests/panic_exit_failure/mod.rs 13_integrated_testing/tests/panic_exit_failure/mod.rs ---- 12_exceptions_part1_groundwork/tests/panic_exit_failure/mod.rs -+++ 13_integrated_testing/tests/panic_exit_failure/mod.rs -@@ -0,0 +1,9 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2020 Andre Richter -+ -+/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -+#[no_mangle] -+fn _panic_exit() -> ! { -+ libkernel::cpu::qemu_exit_failure() -+} - -diff -uNr 12_exceptions_part1_groundwork/tests/panic_exit_success/mod.rs 13_integrated_testing/tests/panic_exit_success/mod.rs ---- 12_exceptions_part1_groundwork/tests/panic_exit_success/mod.rs -+++ 13_integrated_testing/tests/panic_exit_success/mod.rs -@@ -0,0 +1,9 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2020 Andre Richter -+ -+/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -+#[no_mangle] -+fn _panic_exit() -> ! { -+ libkernel::cpu::qemu_exit_success() -+} - -diff -uNr 12_exceptions_part1_groundwork/tests/runner.rb 13_integrated_testing/tests/runner.rb ---- 12_exceptions_part1_groundwork/tests/runner.rb -+++ 13_integrated_testing/tests/runner.rb -@@ -0,0 +1,143 @@ -+#!/usr/bin/env ruby -+# frozen_string_literal: true -+ -+# SPDX-License-Identifier: MIT OR Apache-2.0 -+# -+# Copyright (c) 2019-2020 Andre Richter -+ -+require 'English' -+require 'pty' -+ -+# Test base class. -+class Test -+ INDENT = ' ' -+ -+ def print_border(status) -+ puts -+ puts "#{INDENT}-------------------------------------------------------------------" -+ puts status -+ puts "#{INDENT}-------------------------------------------------------------------\n\n\n" -+ end -+ -+ def print_error(error) -+ puts -+ print_border("#{INDENT}❌ Failure: #{error}: #{@test_name}") -+ end -+ -+ def print_success -+ print_border("#{INDENT}✅ Success: #{@test_name}") -+ end -+ -+ def print_output -+ puts "#{INDENT}-------------------------------------------------------------------" -+ print INDENT -+ print '🦀 ' -+ print @output.join.gsub("\n", "\n#{INDENT}") -+ end -+ -+ def finish(error) -+ print_output -+ -+ exit_code = if error -+ print_error(error) -+ false -+ else -+ print_success -+ true -+ end -+ -+ exit(exit_code) -+ end -+end -+ -+# Executes tests with console I/O. -+class ConsoleTest < Test -+ def initialize(binary, qemu_cmd, test_name, console_subtests) -+ super() -+ -+ @binary = binary -+ @qemu_cmd = qemu_cmd -+ @test_name = test_name -+ @console_subtests = console_subtests -+ @cur_subtest = 1 -+ @output = ["Running #{@console_subtests.length} console-based tests\n", -+ "-------------------------------------------------------------------\n\n"] -+ end -+ -+ def format_test_name(number, name) -+ formatted_name = "#{number.to_s.rjust(3)}. #{name}" -+ formatted_name.ljust(63, '.') -+ end -+ -+ def run_subtest(subtest, qemu_out, qemu_in) -+ @output << format_test_name(@cur_subtest, subtest.name) -+ -+ subtest.run(qemu_out, qemu_in) -+ -+ @output << "[ok]\n" -+ @cur_subtest += 1 -+ end -+ -+ def exec -+ error = false -+ -+ PTY.spawn(@qemu_cmd) do |qemu_out, qemu_in| -+ begin -+ @console_subtests.each { |t| run_subtest(t, qemu_out, qemu_in) } -+ rescue StandardError => e -+ error = e.message -+ end -+ -+ finish(error) -+ end -+ end -+end -+ -+# A wrapper around the bare QEMU invocation. -+class RawTest < Test -+ MAX_WAIT_SECS = 5 -+ -+ def initialize(binary, qemu_cmd, test_name) -+ super() -+ -+ @binary = binary -+ @qemu_cmd = qemu_cmd -+ @test_name = test_name -+ @output = [] -+ end -+ -+ def exec -+ error = 'Timed out waiting for test' -+ io = IO.popen(@qemu_cmd) -+ -+ while IO.select([io], nil, nil, MAX_WAIT_SECS) -+ begin -+ @output << io.read_nonblock(1024) -+ rescue EOFError -+ io.close -+ error = $CHILD_STATUS.to_i != 0 -+ break -+ end -+ end -+ -+ finish(error) -+ end -+end -+ -+##-------------------------------------------------------------------------------------------------- -+## Script entry point -+##-------------------------------------------------------------------------------------------------- -+binary = ARGV.last -+test_name = binary.gsub(modulor{.*deps/}, '').split('-')[0] -+console_test_file = "tests/#{test_name}.rb" -+qemu_cmd = ARGV.join(' ') -+ -+test_runner = if File.exist?(console_test_file) -+ load console_test_file -+ # subtest_collection is provided by console_test_file -+ ConsoleTest.new(binary, qemu_cmd, test_name, subtest_collection) -+ else -+ RawTest.new(binary, qemu_cmd, test_name) -+ end -+ -+test_runner.exec - -diff -uNr 12_exceptions_part1_groundwork/test-types/Cargo.toml 13_integrated_testing/test-types/Cargo.toml ---- 12_exceptions_part1_groundwork/test-types/Cargo.toml -+++ 13_integrated_testing/test-types/Cargo.toml -@@ -0,0 +1,5 @@ -+[package] -+name = "test-types" -+version = "0.1.0" -+authors = ["Andre Richter "] -+edition = "2018" - -diff -uNr 12_exceptions_part1_groundwork/test-types/src/lib.rs 13_integrated_testing/test-types/src/lib.rs ---- 12_exceptions_part1_groundwork/test-types/src/lib.rs -+++ 13_integrated_testing/test-types/src/lib.rs -@@ -0,0 +1,16 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2020 Andre Richter -+ -+//! Types for the `custom_test_frameworks` implementation. -+ -+#![no_std] -+ -+/// Unit test container. -+pub struct UnitTest { -+ /// Name of the test. -+ pub name: &'static str, -+ -+ /// Function pointer to the test. -+ pub test_func: fn(), -+} - -``` diff --git a/13_integrated_testing/build.rs b/13_integrated_testing/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/13_integrated_testing/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/13_integrated_testing/src/_arch/aarch64/cpu.rs b/13_integrated_testing/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 7d146d230..000000000 --- a/13_integrated_testing/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - // Expect the boot core to start in EL2. - if (bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id()) - && (CurrentEL.get() == CurrentEL::EL::EL2.value) - { - el2_to_el1_transition() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -/// Transition from EL2 to EL1. -/// -/// # Safety -/// -/// - The HW state of EL1 must be prepared in a sound way. -/// - Exception return from EL2 must must continue execution in EL1 with -/// `runtime_init::runtime_init()`. -#[inline(always)] -unsafe fn el2_to_el1_transition() -> ! { - use crate::runtime_init; - - // Enable timer counter registers for EL1. - CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); - - // No offset for reading the counters. - CNTVOFF_EL2.set(0); - - // Set EL1 execution state to AArch64. - HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); - - // Set up a simulated exception return. - // - // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a - // stack pointer. - SPSR_EL2.write( - SPSR_EL2::D::Masked - + SPSR_EL2::A::Masked - + SPSR_EL2::I::Masked - + SPSR_EL2::F::Masked - + SPSR_EL2::M::EL1h, - ); - - // Second, let the link register point to runtime_init(). - ELR_EL2.set(runtime_init::runtime_init as *const () as u64); - - // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. - SP_EL1.set(bsp::memory::boot_core_stack_end() as u64); - - // Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. - asm::eret() -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- -use qemu_exit::QEMUExit; - -const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); - -/// Make the host QEMU binary execute `exit(1)`. -pub fn qemu_exit_failure() -> ! { - QEMU_EXIT_HANDLE.exit_failure() -} - -/// Make the host QEMU binary execute `exit(0)`. -pub fn qemu_exit_success() -> ! { - QEMU_EXIT_HANDLE.exit_success() -} diff --git a/13_integrated_testing/src/_arch/aarch64/cpu/smp.rs b/13_integrated_testing/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/13_integrated_testing/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/13_integrated_testing/src/_arch/aarch64/exception.S b/13_integrated_testing/src/_arch/aarch64/exception.S deleted file mode 100644 index ee3b5497e..000000000 --- a/13_integrated_testing/src/_arch/aarch64/exception.S +++ /dev/null @@ -1,138 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -/// Call the function provided by parameter `\handler` after saving the exception context. Provide -/// the context as the first parameter to '\handler'. -.macro CALL_WITH_CONTEXT handler - // Make room on the stack for the exception context. - sub sp, sp, #16 * 17 - - // Store all general purpose registers on the stack. - stp x0, x1, [sp, #16 * 0] - stp x2, x3, [sp, #16 * 1] - stp x4, x5, [sp, #16 * 2] - stp x6, x7, [sp, #16 * 3] - stp x8, x9, [sp, #16 * 4] - stp x10, x11, [sp, #16 * 5] - stp x12, x13, [sp, #16 * 6] - stp x14, x15, [sp, #16 * 7] - stp x16, x17, [sp, #16 * 8] - stp x18, x19, [sp, #16 * 9] - stp x20, x21, [sp, #16 * 10] - stp x22, x23, [sp, #16 * 11] - stp x24, x25, [sp, #16 * 12] - stp x26, x27, [sp, #16 * 13] - stp x28, x29, [sp, #16 * 14] - - // Add the exception link register (ELR_EL1) and the saved program status (SPSR_EL1). - mrs x1, ELR_EL1 - mrs x2, SPSR_EL1 - - stp lr, x1, [sp, #16 * 15] - str x2, [sp, #16 * 16] - - // x0 is the first argument for the function called through `\handler`. - mov x0, sp - - // Call `\handler`. - bl \handler - - // After returning from exception handling code, replay the saved context and return via `eret`. - b __exception_restore_context -.endm - -.macro FIQ_SUSPEND -1: wfe - b 1b -.endm - -//-------------------------------------------------------------------------------------------------- -// The exception vector table. -//-------------------------------------------------------------------------------------------------- -.section .exception_vectors, "ax", @progbits - -// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. -.align 11 - -// Export a symbol for the Rust code to use. -__exception_vector_start: - -// Current exception level with SP_EL0. -// -// .org sets the offset relative to section start. -// -// # Safety -// -// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. -.org 0x000 - CALL_WITH_CONTEXT current_el0_synchronous -.org 0x080 - CALL_WITH_CONTEXT current_el0_irq -.org 0x100 - FIQ_SUSPEND -.org 0x180 - CALL_WITH_CONTEXT current_el0_serror - -// Current exception level with SP_ELx, x > 0. -.org 0x200 - CALL_WITH_CONTEXT current_elx_synchronous -.org 0x280 - CALL_WITH_CONTEXT current_elx_irq -.org 0x300 - FIQ_SUSPEND -.org 0x380 - CALL_WITH_CONTEXT current_elx_serror - -// Lower exception level, AArch64 -.org 0x400 - CALL_WITH_CONTEXT lower_aarch64_synchronous -.org 0x480 - CALL_WITH_CONTEXT lower_aarch64_irq -.org 0x500 - FIQ_SUSPEND -.org 0x580 - CALL_WITH_CONTEXT lower_aarch64_serror - -// Lower exception level, AArch32 -.org 0x600 - CALL_WITH_CONTEXT lower_aarch32_synchronous -.org 0x680 - CALL_WITH_CONTEXT lower_aarch32_irq -.org 0x700 - FIQ_SUSPEND -.org 0x780 - CALL_WITH_CONTEXT lower_aarch32_serror -.org 0x800 - -//-------------------------------------------------------------------------------------------------- -// Helper functions -//-------------------------------------------------------------------------------------------------- -.section .text - -__exception_restore_context: - ldr w19, [sp, #16 * 16] - ldp lr, x20, [sp, #16 * 15] - - msr SPSR_EL1, x19 - msr ELR_EL1, x20 - - ldp x0, x1, [sp, #16 * 0] - ldp x2, x3, [sp, #16 * 1] - ldp x4, x5, [sp, #16 * 2] - ldp x6, x7, [sp, #16 * 3] - ldp x8, x9, [sp, #16 * 4] - ldp x10, x11, [sp, #16 * 5] - ldp x12, x13, [sp, #16 * 6] - ldp x14, x15, [sp, #16 * 7] - ldp x16, x17, [sp, #16 * 8] - ldp x18, x19, [sp, #16 * 9] - ldp x20, x21, [sp, #16 * 10] - ldp x22, x23, [sp, #16 * 11] - ldp x24, x25, [sp, #16 * 12] - ldp x26, x27, [sp, #16 * 13] - ldp x28, x29, [sp, #16 * 14] - - add sp, sp, #16 * 17 - - eret diff --git a/13_integrated_testing/src/_arch/aarch64/exception.rs b/13_integrated_testing/src/_arch/aarch64/exception.rs deleted file mode 100644 index 56f3e6074..000000000 --- a/13_integrated_testing/src/_arch/aarch64/exception.rs +++ /dev/null @@ -1,256 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural synchronous and asynchronous exception handling. - -use core::{cell::UnsafeCell, fmt}; -use cortex_a::{barrier, regs::*}; -use register::InMemoryRegister; - -// Assembly counterpart to this file. -global_asm!(include_str!("exception.S")); - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Wrapper struct for memory copy of SPSR_EL1. -#[repr(transparent)] -struct SpsrEL1(InMemoryRegister); - -/// The exception context as it is stored on the stack on exception entry. -#[repr(C)] -struct ExceptionContext { - /// General Purpose Registers. - gpr: [u64; 30], - - /// The link register, aka x30. - lr: u64, - - /// Exception link register. The program counter at the time the exception happened. - elr_el1: u64, - - /// Saved program status. - spsr_el1: SpsrEL1, -} - -/// Wrapper struct for pretty printing ESR_EL1. -struct EsrEL1; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Prints verbose information about the exception and then panics. -fn default_exception_handler(e: &ExceptionContext) { - panic!( - "\n\nCPU Exception!\n\ - FAR_EL1: {:#018x}\n\ - {}\n\ - {}", - FAR_EL1.get(), - EsrEL1 {}, - e - ); -} - -//------------------------------------------------------------------------------ -// Current, EL0 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn current_el0_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_el0_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_el0_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Current, ELx -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Lower, AArch64 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Lower, AArch32 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Pretty printing -//------------------------------------------------------------------------------ - -/// Human readable ESR_EL1. -#[rustfmt::skip] -impl fmt::Display for EsrEL1 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let esr_el1 = ESR_EL1.extract(); - - // Raw print of whole register. - writeln!(f, "ESR_EL1: {:#010x}", esr_el1.get())?; - - // Raw print of exception class. - write!(f, " Exception Class (EC) : {:#x}", esr_el1.read(ESR_EL1::EC))?; - - // Exception class, translation. - let ec_translation = match esr_el1.read_as_enum(ESR_EL1::EC) { - Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", - _ => "N/A", - }; - writeln!(f, " - {}", ec_translation)?; - - // Raw print of instruction specific syndrome. - write!(f, " Instr Specific Syndrome (ISS): {:#x}", esr_el1.read(ESR_EL1::ISS))?; - - Ok(()) - } -} - -/// Human readable SPSR_EL1. -#[rustfmt::skip] -impl fmt::Display for SpsrEL1 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Raw value. - writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; - - let to_flag_str = |x| -> _ { - if x { "Set" } else { "Not set" } - }; - - writeln!(f, " Flags:")?; - writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; - writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; - writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; - writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - writeln!(f, " Exception handling state:")?; - writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; - writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; - writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; - writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; - - write!(f, " Illegal Execution State (IL): {}", - to_flag_str(self.0.is_set(SPSR_EL1::IL)) - )?; - - Ok(()) - } -} - -/// Human readable print of the exception context. -impl fmt::Display for ExceptionContext { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; - writeln!(f, "{}", self.spsr_el1)?; - writeln!(f)?; - writeln!(f, "General purpose register:")?; - - #[rustfmt::skip] - let alternating = |x| -> _ { - if x % 2 == 0 { " " } else { "\n" } - }; - - // Print two registers per line. - for (i, reg) in self.gpr.iter().enumerate() { - write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; - } - write!(f, " lr : {:#018x}", self.lr)?; - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use crate::exception::PrivilegeLevel; - -/// The processing element's current privilege level. -pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { - let el = CurrentEL.read_as_enum(CurrentEL::EL); - match el { - Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), - Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), - Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), - _ => (PrivilegeLevel::Unknown, "Unknown"), - } -} - -/// Init exception handling by setting the exception vector base address register. -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must -/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference -/// Manual. -pub unsafe fn handling_init() { - // Provided by exception.S. - extern "Rust" { - static __exception_vector_start: UnsafeCell<()>; - } - - VBAR_EL1.set(__exception_vector_start.get() as u64); - - // Force VBAR update to complete before next instruction. - barrier::isb(barrier::SY); -} diff --git a/13_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs b/13_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs deleted file mode 100644 index f660544c1..000000000 --- a/13_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural asynchronous exception handling. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -trait DaifField { - fn daif_field() -> register::Field; -} - -struct Debug; -struct SError; -struct IRQ; -struct FIQ; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl DaifField for Debug { - fn daif_field() -> register::Field { - DAIF::D - } -} - -impl DaifField for SError { - fn daif_field() -> register::Field { - DAIF::A - } -} - -impl DaifField for IRQ { - fn daif_field() -> register::Field { - DAIF::I - } -} - -impl DaifField for FIQ { - fn daif_field() -> register::Field { - DAIF::F - } -} - -fn is_masked() -> bool -where - T: DaifField, -{ - DAIF.is_set(T::daif_field()) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Print the AArch64 exceptions status. -#[rustfmt::skip] -pub fn print_state() { - use crate::info; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - info!(" Debug: {}", to_mask_str(is_masked::())); - info!(" SError: {}", to_mask_str(is_masked::())); - info!(" IRQ: {}", to_mask_str(is_masked::())); - info!(" FIQ: {}", to_mask_str(is_masked::())); -} diff --git a/13_integrated_testing/src/_arch/aarch64/memory/mmu.rs b/13_integrated_testing/src/_arch/aarch64/memory/mmu.rs deleted file mode 100644 index 1ccb3fd71..000000000 --- a/13_integrated_testing/src/_arch/aarch64/memory/mmu.rs +++ /dev/null @@ -1,370 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management Unit Driver. -//! -//! Static translation tables, compiled on boot; Everything 64 KiB granule. - -use super::{AccessPermissions, AttributeFields, MemAttributes}; -use crate::{bsp, memory}; -use core::convert; -use cortex_a::{barrier, regs::*}; -use register::{register_bitfields, InMemoryRegister}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. -register_bitfields! {u64, - STAGE1_TABLE_DESCRIPTOR [ - /// Physical address of the next descriptor. - NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. -register_bitfields! {u64, - STAGE1_PAGE_DESCRIPTOR [ - /// Privileged execute-never. - PXN OFFSET(53) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). - OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - /// Access flag. - AF OFFSET(10) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Shareability field. - SH OFFSET(8) NUMBITS(2) [ - OuterShareable = 0b10, - InnerShareable = 0b11 - ], - - /// Access Permissions. - AP OFFSET(6) NUMBITS(2) [ - RW_EL1 = 0b00, - RW_EL1_EL0 = 0b01, - RO_EL1 = 0b10, - RO_EL1_EL0 = 0b11 - ], - - /// Memory attributes index into the MAIR_EL1 register. - AttrIndx OFFSET(2) NUMBITS(3) [], - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -const SIXTYFOUR_KIB_SHIFT: usize = 16; // log2(64 * 1024) -const FIVETWELVE_MIB_SHIFT: usize = 29; // log2(512 * 1024 * 1024) - -/// A table descriptor for 64 KiB aperture. -/// -/// The output points to the next table. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct TableDescriptor(u64); - -/// A page descriptor with 64 KiB aperture. -/// -/// The output points to physical memory. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct PageDescriptor(u64); - -/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB -/// aligned, hence the "reverse" order of appearance. -#[repr(C)] -#[repr(align(65536))] -struct FixedSizeTranslationTable { - /// Page descriptors, covering 64 KiB windows per entry. - lvl3: [[PageDescriptor; 8192]; NUM_TABLES], - - /// Table descriptors, covering 512 MiB windows. - lvl2: [TableDescriptor; NUM_TABLES], -} - -/// Usually evaluates to 1 GiB for RPi3 and 4 GiB for RPi 4. -const NUM_LVL2_TABLES: usize = bsp::memory::mmu::addr_space_size() >> FIVETWELVE_MIB_SHIFT; -type ArchTranslationTable = FixedSizeTranslationTable; - -trait BaseAddr { - fn base_addr_u64(&self) -> u64; - fn base_addr_usize(&self) -> usize; -} - -/// Constants for indexing the MAIR_EL1. -#[allow(dead_code)] -mod mair { - pub const DEVICE: u64 = 0; - pub const NORMAL: u64 = 1; -} - -/// Memory Management Unit type. -struct MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -/// The translation tables. -/// -/// # Safety -/// -/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". -static mut KERNEL_TABLES: ArchTranslationTable = ArchTranslationTable::new(); - -static MMU: MemoryManagementUnit = MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl BaseAddr for [T; N] { - fn base_addr_u64(&self) -> u64 { - self as *const T as u64 - } - - fn base_addr_usize(&self) -> usize { - self as *const _ as usize - } -} - -impl convert::From for TableDescriptor { - fn from(next_lvl_table_addr: usize) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = next_lvl_table_addr >> SIXTYFOUR_KIB_SHIFT; - val.write( - STAGE1_TABLE_DESCRIPTOR::VALID::True - + STAGE1_TABLE_DESCRIPTOR::TYPE::Table - + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64), - ); - - TableDescriptor(val.get()) - } -} - -/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. -impl convert::From - for register::FieldValue -{ - fn from(attribute_fields: AttributeFields) -> Self { - // Memory attributes. - let mut desc = match attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => { - STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::NORMAL) - } - MemAttributes::Device => { - STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::DEVICE) - } - }; - - // Access Permissions. - desc += match attribute_fields.acc_perms { - AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, - AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, - }; - - // Execute Never. - desc += if attribute_fields.execute_never { - STAGE1_PAGE_DESCRIPTOR::PXN::True - } else { - STAGE1_PAGE_DESCRIPTOR::PXN::False - }; - - desc - } -} - -impl PageDescriptor { - /// Create an instance. - fn new(output_addr: usize, attribute_fields: AttributeFields) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = output_addr as u64 >> SIXTYFOUR_KIB_SHIFT; - val.write( - STAGE1_PAGE_DESCRIPTOR::VALID::True - + STAGE1_PAGE_DESCRIPTOR::AF::True - + attribute_fields.into() - + STAGE1_PAGE_DESCRIPTOR::TYPE::Table - + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted), - ); - - Self(val.get()) - } -} - -impl FixedSizeTranslationTable<{ NUM_TABLES }> { - /// Create an instance. - pub const fn new() -> Self { - assert!(NUM_TABLES > 0); - - Self { - lvl3: [[PageDescriptor(0); 8192]; NUM_TABLES], - lvl2: [TableDescriptor(0); NUM_TABLES], - } - } -} - -/// Setup function for the MAIR_EL1 register. -fn set_up_mair() { - // Define the memory types being mapped. - MAIR_EL1.write( - // Attribute 1 - Cacheable normal DRAM. - MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + - MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + - - // Attribute 0 - Device. - MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, - ); -} - -/// Iterates over all static translation table entries and fills them at once. -/// -/// # Safety -/// -/// - Modifies a `static mut`. Ensure it only happens from here. -unsafe fn populate_tt_entries() -> Result<(), &'static str> { - for (l2_nr, l2_entry) in KERNEL_TABLES.lvl2.iter_mut().enumerate() { - *l2_entry = KERNEL_TABLES.lvl3[l2_nr].base_addr_usize().into(); - - for (l3_nr, l3_entry) in KERNEL_TABLES.lvl3[l2_nr].iter_mut().enumerate() { - let virt_addr = (l2_nr << FIVETWELVE_MIB_SHIFT) + (l3_nr << SIXTYFOUR_KIB_SHIFT); - - let (output_addr, attribute_fields) = - bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; - - *l3_entry = PageDescriptor::new(output_addr, attribute_fields); - } - } - - Ok(()) -} - -/// Configure various settings of stage 1 of the EL1 translation regime. -fn configure_translation_control() { - let ips = ID_AA64MMFR0_EL1.read(ID_AA64MMFR0_EL1::PARange); - - TCR_EL1.write( - TCR_EL1::TBI0::Ignored - + TCR_EL1::IPS.val(ips) - + TCR_EL1::TG0::KiB_64 - + TCR_EL1::SH0::Inner - + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::EPD0::EnableTTBR0Walks - + TCR_EL1::T0SZ.val(32), // TTBR0 spans 4 GiB total. - ); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the MMU instance. -pub fn mmu() -> &'static impl memory::mmu::interface::MMU { - &MMU -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl memory::mmu::interface::MMU for MemoryManagementUnit { - unsafe fn init(&self) -> Result<(), &'static str> { - // Fail early if translation granule is not supported. Both RPis support it, though. - if !ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported) { - return Err("Translation granule not supported in HW"); - } - - // Prepare the memory attribute indirection register. - set_up_mair(); - - // Populate translation tables. - populate_tt_entries()?; - - // Set the "Translation Table Base Register". - TTBR0_EL1.set_baddr(KERNEL_TABLES.lvl2.base_addr_u64()); - - configure_translation_control(); - - // Switch the MMU on. - // - // First, force all previous changes to be seen before the MMU is enabled. - barrier::isb(barrier::SY); - - // Enable the MMU and turn on data and instruction caching. - SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); - - // Force MMU init to complete before next instruction. - barrier::isb(barrier::SY); - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check if the size of `struct TableDescriptor` is as expected. - #[kernel_test] - fn size_of_tabledescriptor_equals_64_bit() { - assert_eq!( - core::mem::size_of::(), - core::mem::size_of::() - ); - } - - /// Check if the size of `struct PageDescriptor` is as expected. - #[kernel_test] - fn size_of_pagedescriptor_equals_64_bit() { - assert_eq!( - core::mem::size_of::(), - core::mem::size_of::() - ); - } - - /// Check if KERNEL_TABLES is in .bss. - #[kernel_test] - fn kernel_tables_in_bss() { - let bss_range = bsp::memory::bss_range_inclusive(); - let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; - - assert!(bss_range.contains(&kernel_tables_addr)); - } -} diff --git a/13_integrated_testing/src/_arch/aarch64/time.rs b/13_integrated_testing/src/_arch/aarch64/time.rs deleted file mode 100644 index af98ddd01..000000000 --- a/13_integrated_testing/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) - } - - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; - - Duration::from_nanos(current_count / frq) - } - - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } - - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get() as u64; - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; - } - - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); - - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); - - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} - - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); - } -} diff --git a/13_integrated_testing/src/bsp.rs b/13_integrated_testing/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/13_integrated_testing/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/13_integrated_testing/src/bsp/device_driver.rs b/13_integrated_testing/src/bsp/device_driver.rs deleted file mode 100644 index ce7396f22..000000000 --- a/13_integrated_testing/src/bsp/device_driver.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/13_integrated_testing/src/bsp/device_driver/bcm.rs b/13_integrated_testing/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 59071d5d8..000000000 --- a/13_integrated_testing/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index 15bd3b78b..000000000 --- a/13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; - use core::time::Duration; - - // The Linux 2837 GPIO driver waits 1 µs between the steps. - const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index e39bc7cdb..000000000 --- a/13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,323 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => _reserved3), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Read one character. - let mut ret = inner.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - inner.chars_read += 1; - - ret - }) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} diff --git a/13_integrated_testing/src/bsp/device_driver/common.rs b/13_integrated_testing/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/13_integrated_testing/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/13_integrated_testing/src/bsp/raspberrypi.rs b/13_integrated_testing/src/bsp/raspberrypi.rs deleted file mode 100644 index 10888d37f..000000000 --- a/13_integrated_testing/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/13_integrated_testing/src/bsp/raspberrypi/console.rs b/13_integrated_testing/src/bsp/raspberrypi/console.rs deleted file mode 100644 index 16b2f59bc..000000000 --- a/13_integrated_testing/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps -/// than on real hardware due to QEMU's abstractions. -/// -/// For the RPi, nothing needs to be done. -pub fn qemu_bring_up_console() {} diff --git a/13_integrated_testing/src/bsp/raspberrypi/cpu.rs b/13_integrated_testing/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/13_integrated_testing/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/13_integrated_testing/src/bsp/raspberrypi/driver.rs b/13_integrated_testing/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index fe24dd71b..000000000 --- a/13_integrated_testing/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/13_integrated_testing/src/bsp/raspberrypi/link.ld b/13_integrated_testing/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 90d096ffe..000000000 --- a/13_integrated_testing/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,47 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - __ro_start = .; - .text : - { - *(.text._start) *(.text*) - } - - .exception_vectors : - { - *(.exception_vectors*) - } - - .rodata : - { - *(.rodata*) - } - . = ALIGN(65536); /* Fill up to 64 KiB */ - __ro_end = .; - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/13_integrated_testing/src/bsp/raspberrypi/memory.rs b/13_integrated_testing/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 810acd8af..000000000 --- a/13_integrated_testing/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -pub mod mmu; - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; - static __ro_start: UnsafeCell<()>; - static __ro_end: UnsafeCell<()>; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; - - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const END_INCLUSIVE: usize = 0x4000_FFFF; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const END_INCLUSIVE: usize = 0xFF84_FFFF; - } -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Start address of the Read-Only (RO) range. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_start() -> usize { - unsafe { __ro_start.get() as usize } -} - -/// Size of the Read-Only (RO) range of the kernel binary. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_end() -> usize { - unsafe { __ro_end.get() as usize } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/13_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs b/13_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs deleted file mode 100644 index d5078b5a0..000000000 --- a/13_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs +++ /dev/null @@ -1,116 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management Unit. - -use super::map as memory_map; -use crate::memory::mmu::*; -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -const NUM_MEM_RANGES: usize = 2; - -/// The virtual memory layout. -/// -/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. -/// It is agnostic of the paging granularity that the architecture's MMU will use. -pub static LAYOUT: KernelVirtualLayout<{ NUM_MEM_RANGES }> = KernelVirtualLayout::new( - memory_map::END_INCLUSIVE, - [ - TranslationDescriptor { - name: "Kernel code and RO data", - virtual_range: ro_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadOnly, - execute_never: false, - }, - }, - TranslationDescriptor { - name: "Device MMIO", - virtual_range: mmio_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - }, - ], -); - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn ro_range_inclusive() -> RangeInclusive { - // Notice the subtraction to turn the exclusive end into an inclusive end. - #[allow(clippy::range_minus_one)] - RangeInclusive::new(super::ro_start(), super::ro_end() - 1) -} - -fn mmio_range_inclusive() -> RangeInclusive { - RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the address space size in bytes. -pub const fn addr_space_size() -> usize { - memory_map::END_INCLUSIVE + 1 -} - -/// Return a reference to the virtual memory layout. -pub fn virt_mem_layout() -> &'static KernelVirtualLayout<{ NUM_MEM_RANGES }> { - &LAYOUT -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check alignment of the kernel's virtual memory layout sections. - #[kernel_test] - fn virt_mem_layout_sections_are_64KiB_aligned() { - const SIXTYFOUR_KIB: usize = 65536; - - for i in LAYOUT.inner().iter() { - let start: usize = *(i.virtual_range)().start(); - let end: usize = *(i.virtual_range)().end() + 1; - - assert_eq!(start % SIXTYFOUR_KIB, 0); - assert_eq!(end % SIXTYFOUR_KIB, 0); - assert!(end >= start); - } - } - - /// Ensure the kernel's virtual memory layout is free of overlaps. - #[kernel_test] - fn virt_mem_layout_has_no_overlaps() { - let layout = virt_mem_layout().inner(); - - for (i, first) in layout.iter().enumerate() { - for second in layout.iter().skip(i + 1) { - let first_range = first.virtual_range; - let second_range = second.virtual_range; - - assert!(!first_range().contains(second_range().start())); - assert!(!first_range().contains(second_range().end())); - assert!(!second_range().contains(first_range().start())); - assert!(!second_range().contains(first_range().end())); - } - } - } -} diff --git a/13_integrated_testing/src/console.rs b/13_integrated_testing/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/13_integrated_testing/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/13_integrated_testing/src/cpu.rs b/13_integrated_testing/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/13_integrated_testing/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/13_integrated_testing/src/cpu/smp.rs b/13_integrated_testing/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/13_integrated_testing/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/13_integrated_testing/src/driver.rs b/13_integrated_testing/src/driver.rs deleted file mode 100644 index e2875b876..000000000 --- a/13_integrated_testing/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/13_integrated_testing/src/exception.rs b/13_integrated_testing/src/exception.rs deleted file mode 100644 index 81ea2b26e..000000000 --- a/13_integrated_testing/src/exception.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronous and asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/exception.rs"] -mod arch_exception; -pub use arch_exception::*; - -pub mod asynchronous; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Kernel privilege levels. -#[allow(missing_docs)] -#[derive(PartialEq)] -pub enum PrivilegeLevel { - User, - Kernel, - Hypervisor, - Unknown, -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Libkernel unit tests must execute in kernel mode. - #[kernel_test] - fn test_runner_executes_in_kernel_mode() { - let (level, _) = current_privilege_level(); - - assert!(level == PrivilegeLevel::Kernel) - } -} diff --git a/13_integrated_testing/src/exception/asynchronous.rs b/13_integrated_testing/src/exception/asynchronous.rs deleted file mode 100644 index 3c75f90a2..000000000 --- a/13_integrated_testing/src/exception/asynchronous.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/exception/asynchronous.rs"] -mod arch_exception_async; -pub use arch_exception_async::*; diff --git a/13_integrated_testing/src/lib.rs b/13_integrated_testing/src/lib.rs deleted file mode 100644 index 19e6f24fc..000000000 --- a/13_integrated_testing/src/lib.rs +++ /dev/null @@ -1,170 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` library. -//! -//! Used by `main.rs` to compose the final kernel binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![allow(incomplete_features)] -#![feature(const_fn_fn_ptr_basics)] -#![feature(const_generics)] -#![feature(const_panic)] -#![feature(format_args_nl)] -#![feature(global_asm)] -#![feature(linkage)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_std] -// Testing -#![cfg_attr(test, no_main)] -#![feature(custom_test_frameworks)] -#![reexport_test_harness_main = "test_main"] -#![test_runner(crate::test_runner)] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()` (defined in `main.rs`). - -mod panic_wait; -mod runtime_init; -mod synchronization; - -pub mod bsp; -pub mod console; -pub mod cpu; -pub mod driver; -pub mod exception; -pub mod memory; -pub mod print; -pub mod time; - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// The default runner for unit tests. -pub fn test_runner(tests: &[&test_types::UnitTest]) { - println!("Running {} tests", tests.len()); - println!("-------------------------------------------------------------------\n"); - for (i, test) in tests.iter().enumerate() { - print!("{:>3}. {:.<58}", i + 1, test.name); - - // Run the actual test. - (test.test_func)(); - - // Failed tests call panic!(). Execution reaches here only if the test has passed. - println!("[ok]") - } -} - -/// The `kernel_init()` for unit tests. Called from `runtime_init()`. -#[cfg(test)] -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - test_main(); - - cpu::qemu_exit_success() -} diff --git a/13_integrated_testing/src/main.rs b/13_integrated_testing/src/main.rs deleted file mode 100644 index 250172057..000000000 --- a/13_integrated_testing/src/main.rs +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -use libkernel::{bsp, console, driver, exception, info, memory, time}; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order: -/// - Virtual memory must be activated before the device drivers. -/// - Without it, any atomic operations, e.g. the yet-to-be-introduced spinlocks in the device -/// drivers (which currently employ NullLocks instead of spinlocks), will fail to work on -/// the RPi SoCs. -#[no_mangle] -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - use memory::mmu::interface::MMU; - - exception::handling_init(); - - if let Err(string) = memory::mmu::mmu().init() { - panic!("MMU: {}", string); - } - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use console::interface::All; - use driver::interface::DriverManager; - - info!("Booting on: {}", bsp::board_name()); - - info!("MMU online. Special regions:"); - bsp::memory::mmu::virt_mem_layout().print_layout(); - - let (_, privilege_level) = exception::current_privilege_level(); - info!("Current privilege level: {}", privilege_level); - - info!("Exception handling state:"); - exception::asynchronous::print_state(); - - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() - ); - - info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } - - info!("Echoing input now"); - loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); - } -} diff --git a/13_integrated_testing/src/memory.rs b/13_integrated_testing/src/memory.rs deleted file mode 100644 index 32353d4f6..000000000 --- a/13_integrated_testing/src/memory.rs +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -pub mod mmu; - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check `zero_volatile()`. - #[kernel_test] - fn zero_volatile_works() { - let mut x: [usize; 3] = [10, 11, 12]; - let x_range = x.as_mut_ptr_range(); - let x_range_inclusive = - RangeInclusive::new(x_range.start, unsafe { x_range.end.offset(-1) }); - - unsafe { zero_volatile(x_range_inclusive) }; - - assert_eq!(x, [0, 0, 0]); - } - - /// Check `bss` section layout. - #[kernel_test] - fn bss_section_is_sane() { - use crate::bsp::memory::bss_range_inclusive; - use core::mem; - - let start = *bss_range_inclusive().start() as usize; - let end = *bss_range_inclusive().end() as usize; - - assert_eq!(start % mem::size_of::(), 0); - assert_eq!(end % mem::size_of::(), 0); - assert!(end >= start); - } -} diff --git a/13_integrated_testing/src/memory/mmu.rs b/13_integrated_testing/src/memory/mmu.rs deleted file mode 100644 index 39f3ef3cd..000000000 --- a/13_integrated_testing/src/memory/mmu.rs +++ /dev/null @@ -1,204 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Memory Management Unit. -//! -//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file -//! provides types for composing an architecture-agnostic description of the kernel 's virtual -//! memory layout. -//! -//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` -//! function. -//! -//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and -//! install respective translation tables. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/memory/mmu.rs"] -mod arch_mmu; -pub use arch_mmu::*; - -use core::{fmt, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Memory Management interfaces. -pub mod interface { - - /// MMU functions. - pub trait MMU { - /// Called by the kernel during early init. Supposed to take the translation tables from the - /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. - /// - /// # Safety - /// - /// - Changes the HW's global state. - unsafe fn init(&self) -> Result<(), &'static str>; - } -} - -/// Architecture agnostic translation types. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum Translation { - Identity, - Offset(usize), -} - -/// Architecture agnostic memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum MemAttributes { - CacheableDRAM, - Device, -} - -/// Architecture agnostic access permissions. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum AccessPermissions { - ReadOnly, - ReadWrite, -} - -/// Collection of memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub struct AttributeFields { - pub mem_attributes: MemAttributes, - pub acc_perms: AccessPermissions, - pub execute_never: bool, -} - -/// Architecture agnostic descriptor for a memory range. -#[allow(missing_docs)] -pub struct TranslationDescriptor { - pub name: &'static str, - pub virtual_range: fn() -> RangeInclusive, - pub physical_range_translation: Translation, - pub attribute_fields: AttributeFields, -} - -/// Type for expressing the kernel's virtual memory layout. -pub struct KernelVirtualLayout { - /// The last (inclusive) address of the address space. - max_virt_addr_inclusive: usize, - - /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. - inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl Default for AttributeFields { - fn default() -> AttributeFields { - AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - } - } -} - -/// Human-readable output of a TranslationDescriptor. -impl fmt::Display for TranslationDescriptor { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Call the function to which self.range points, and dereference the result, which causes - // Rust to copy the value. - let start = *(self.virtual_range)().start(); - let end = *(self.virtual_range)().end(); - let size = end - start + 1; - - // log2(1024). - const KIB_RSHIFT: u32 = 10; - - // log2(1024 * 1024). - const MIB_RSHIFT: u32 = 20; - - let (size, unit) = if (size >> MIB_RSHIFT) > 0 { - (size >> MIB_RSHIFT, "MiB") - } else if (size >> KIB_RSHIFT) > 0 { - (size >> KIB_RSHIFT, "KiB") - } else { - (size, "Byte") - }; - - let attr = match self.attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => "C", - MemAttributes::Device => "Dev", - }; - - let acc_p = match self.attribute_fields.acc_perms { - AccessPermissions::ReadOnly => "RO", - AccessPermissions::ReadWrite => "RW", - }; - - let xn = if self.attribute_fields.execute_never { - "PXN" - } else { - "PX" - }; - - write!( - f, - " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", - start, end, size, unit, attr, acc_p, xn, self.name - ) - } -} - -impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { - /// Create a new instance. - pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { - Self { - max_virt_addr_inclusive: max, - inner: layout, - } - } - - /// For a virtual address, find and return the physical output address and corresponding - /// attributes. - /// - /// If the address is not found in `inner`, return an identity mapped default with normal - /// cacheable DRAM attributes. - pub fn virt_addr_properties( - &self, - virt_addr: usize, - ) -> Result<(usize, AttributeFields), &'static str> { - if virt_addr > self.max_virt_addr_inclusive { - return Err("Address out of range"); - } - - for i in self.inner.iter() { - if (i.virtual_range)().contains(&virt_addr) { - let output_addr = match i.physical_range_translation { - Translation::Identity => virt_addr, - Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), - }; - - return Ok((output_addr, i.attribute_fields)); - } - } - - Ok((virt_addr, AttributeFields::default())) - } - - /// Print the memory layout. - pub fn print_layout(&self) { - use crate::info; - - for i in self.inner.iter() { - info!("{}", i); - } - } - - #[cfg(test)] - pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { - &self.inner - } -} diff --git a/13_integrated_testing/src/panic_wait.rs b/13_integrated_testing/src/panic_wait.rs deleted file mode 100644 index 218c0a884..000000000 --- a/13_integrated_testing/src/panic_wait.rs +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// The point of exit for the "standard" (non-testing) `libkernel`. -/// -/// This code will be used by the release kernel binary and the `integration tests`. It is linked -/// weakly, so that the integration tests can overload it to exit `QEMU` instead of spinning -/// forever. -/// -/// This is one possible approach to solve the problem that `cargo` can not know who the consumer of -/// the library will be: -/// - The release kernel binary that should safely park the paniced core, -/// - or an `integration test` that is executed in QEMU, which should just exit QEMU. -#[cfg(not(test))] -#[linkage = "weak"] -#[no_mangle] -fn _panic_exit() -> ! { - cpu::wait_forever() -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - _panic_exit() -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// The point of exit when the library is compiled for testing. -#[cfg(test)] -#[no_mangle] -fn _panic_exit() -> ! { - cpu::qemu_exit_failure() -} diff --git a/13_integrated_testing/src/print.rs b/13_integrated_testing/src/print.rs deleted file mode 100644 index 8b6f3f988..000000000 --- a/13_integrated_testing/src/print.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} - -/// Prints an info, with a newline. -#[macro_export] -macro_rules! info { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} - -/// Prints a warning, with a newline. -#[macro_export] -macro_rules! warn { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} diff --git a/13_integrated_testing/src/runtime_init.rs b/13_integrated_testing/src/runtime_init.rs deleted file mode 100644 index 1306578dd..000000000 --- a/13_integrated_testing/src/runtime_init.rs +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - extern "Rust" { - fn kernel_init() -> !; - } - - zero_bss(); - kernel_init() -} diff --git a/13_integrated_testing/src/synchronization.rs b/13_integrated_testing/src/synchronization.rs deleted file mode 100644 index 6de32807c..000000000 --- a/13_integrated_testing/src/synchronization.rs +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} - -impl NullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl interface::Mutex for NullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - f(data) - } -} diff --git a/13_integrated_testing/src/time.rs b/13_integrated_testing/src/time.rs deleted file mode 100644 index cd3ceec33..000000000 --- a/13_integrated_testing/src/time.rs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; -pub use arch_time::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); - } -} diff --git a/13_integrated_testing/test-macros/Cargo.toml b/13_integrated_testing/test-macros/Cargo.toml deleted file mode 100644 index a570f72b4..000000000 --- a/13_integrated_testing/test-macros/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "test-macros" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1.x" -quote = "1.x" -syn = { version = "1.x", features = ["full"] } -test-types = { path = "../test-types" } diff --git a/13_integrated_testing/test-macros/src/lib.rs b/13_integrated_testing/test-macros/src/lib.rs deleted file mode 100644 index 092c4806e..000000000 --- a/13_integrated_testing/test-macros/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -use proc_macro::TokenStream; -use proc_macro2::Span; -use quote::quote; -use syn::{parse_macro_input, Ident, ItemFn}; - -#[proc_macro_attribute] -pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { - let f = parse_macro_input!(input as ItemFn); - - let test_name = &format!("{}", f.sig.ident.to_string()); - let test_ident = Ident::new( - &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), - Span::call_site(), - ); - let test_code_block = f.block; - - quote!( - #[test_case] - const #test_ident: test_types::UnitTest = test_types::UnitTest { - name: #test_name, - test_func: || #test_code_block, - }; - ) - .into() -} diff --git a/13_integrated_testing/test-types/Cargo.toml b/13_integrated_testing/test-types/Cargo.toml deleted file mode 100644 index a0be2c57c..000000000 --- a/13_integrated_testing/test-types/Cargo.toml +++ /dev/null @@ -1,5 +0,0 @@ -[package] -name = "test-types" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" diff --git a/13_integrated_testing/test-types/src/lib.rs b/13_integrated_testing/test-types/src/lib.rs deleted file mode 100644 index 371bb5574..000000000 --- a/13_integrated_testing/test-types/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Types for the `custom_test_frameworks` implementation. - -#![no_std] - -/// Unit test container. -pub struct UnitTest { - /// Name of the test. - pub name: &'static str, - - /// Function pointer to the test. - pub test_func: fn(), -} diff --git a/13_integrated_testing/tests/00_console_sanity.rb b/13_integrated_testing/tests/00_console_sanity.rb deleted file mode 100644 index a6b549b2a..000000000 --- a/13_integrated_testing/tests/00_console_sanity.rb +++ /dev/null @@ -1,50 +0,0 @@ -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2019-2020 Andre Richter - -require 'expect' - -TIMEOUT_SECS = 3 - -# Verify sending and receiving works as expected. -class TxRxHandshake - def name - 'Transmit and Receive handshake' - end - - def run(qemu_out, qemu_in) - qemu_in.write_nonblock('ABC') - raise('TX/RX test failed') if qemu_out.expect('OK1234', TIMEOUT_SECS).nil? - end -end - -# Check for correct TX statistics implementation. Depends on test 1 being run first. -class TxStatistics - def name - 'Transmit statistics' - end - - def run(qemu_out, _qemu_in) - raise('chars_written reported wrong') if qemu_out.expect('6', TIMEOUT_SECS).nil? - end -end - -# Check for correct RX statistics implementation. Depends on test 1 being run first. -class RxStatistics - def name - 'Receive statistics' - end - - def run(qemu_out, _qemu_in) - raise('chars_read reported wrong') if qemu_out.expect('3', TIMEOUT_SECS).nil? - end -end - -##-------------------------------------------------------------------------------------------------- -## Test registration -##-------------------------------------------------------------------------------------------------- -def subtest_collection - [TxRxHandshake.new, TxStatistics.new, RxStatistics.new] -end diff --git a/13_integrated_testing/tests/00_console_sanity.rs b/13_integrated_testing/tests/00_console_sanity.rs deleted file mode 100644 index 5aa38f098..000000000 --- a/13_integrated_testing/tests/00_console_sanity.rs +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Console sanity tests - RX, TX and statistics. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -mod panic_exit_failure; - -use libkernel::{bsp, console, print}; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - use bsp::console::{console, qemu_bring_up_console}; - use console::interface::*; - - qemu_bring_up_console(); - - // Handshake - assert_eq!(console().read_char(), 'A'); - assert_eq!(console().read_char(), 'B'); - assert_eq!(console().read_char(), 'C'); - print!("OK1234"); - - // 6 - print!("{}", console().chars_written()); - - // 3 - print!("{}", console().chars_read()); - - // The QEMU process running this test will be closed by the I/O test harness. - loop {} -} diff --git a/13_integrated_testing/tests/01_timer_sanity.rs b/13_integrated_testing/tests/01_timer_sanity.rs deleted file mode 100644 index e0b3c1622..000000000 --- a/13_integrated_testing/tests/01_timer_sanity.rs +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Timer sanity tests. - -#![feature(custom_test_frameworks)] -#![no_main] -#![no_std] -#![reexport_test_harness_main = "test_main"] -#![test_runner(libkernel::test_runner)] - -mod panic_exit_failure; - -use core::time::Duration; -use libkernel::{bsp, cpu, time, time::interface::TimeManager}; -use test_macros::kernel_test; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. - - test_main(); - - cpu::qemu_exit_success() -} - -/// Simple check that the timer is running. -#[kernel_test] -fn timer_is_counting() { - assert!(time::time_manager().uptime().as_nanos() > 0) -} - -/// Timer resolution must be sufficient. -#[kernel_test] -fn timer_resolution_is_sufficient() { - assert!(time::time_manager().resolution().as_nanos() < 100) -} - -/// Sanity check spin_for() implementation. -#[kernel_test] -fn spin_accuracy_check_1_second() { - let t1 = time::time_manager().uptime(); - time::time_manager().spin_for(Duration::from_secs(1)); - let t2 = time::time_manager().uptime(); - - assert_eq!((t2 - t1).as_secs(), 1) -} diff --git a/13_integrated_testing/tests/02_exception_sync_page_fault.rs b/13_integrated_testing/tests/02_exception_sync_page_fault.rs deleted file mode 100644 index 64fc5486e..000000000 --- a/13_integrated_testing/tests/02_exception_sync_page_fault.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Page faults must result in synchronous exceptions. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -/// -/// Reaching this code is a success, because it is called from the synchronous exception handler, -/// which is what this test wants to achieve. -/// -/// It also means that this integration test can not use any other code that calls panic!() directly -/// or indirectly. -mod panic_exit_success; - -use libkernel::{bsp, cpu, exception, memory, println}; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - use memory::mmu::interface::MMU; - - bsp::console::qemu_bring_up_console(); - - println!("Testing synchronous exception handling by causing a page fault"); - println!("-------------------------------------------------------------------\n"); - - exception::handling_init(); - - if let Err(string) = memory::mmu::mmu().init() { - println!("MMU: {}", string); - cpu::qemu_exit_failure() - } - - println!("Writing beyond mapped area to address 9 GiB..."); - let big_addr: u64 = 9 * 1024 * 1024 * 1024; - core::ptr::read_volatile(big_addr as *mut u64); - - // If execution reaches here, the memory access above did not cause a page fault exception. - cpu::qemu_exit_failure() -} diff --git a/13_integrated_testing/tests/panic_exit_failure/mod.rs b/13_integrated_testing/tests/panic_exit_failure/mod.rs deleted file mode 100644 index b4ac73d1e..000000000 --- a/13_integrated_testing/tests/panic_exit_failure/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -#[no_mangle] -fn _panic_exit() -> ! { - libkernel::cpu::qemu_exit_failure() -} diff --git a/13_integrated_testing/tests/panic_exit_success/mod.rs b/13_integrated_testing/tests/panic_exit_success/mod.rs deleted file mode 100644 index 54bb072d7..000000000 --- a/13_integrated_testing/tests/panic_exit_success/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -#[no_mangle] -fn _panic_exit() -> ! { - libkernel::cpu::qemu_exit_success() -} diff --git a/13_integrated_testing/tests/runner.rb b/13_integrated_testing/tests/runner.rb deleted file mode 100755 index 2a0aa393e..000000000 --- a/13_integrated_testing/tests/runner.rb +++ /dev/null @@ -1,143 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2019-2020 Andre Richter - -require 'English' -require 'pty' - -# Test base class. -class Test - INDENT = ' ' - - def print_border(status) - puts - puts "#{INDENT}-------------------------------------------------------------------" - puts status - puts "#{INDENT}-------------------------------------------------------------------\n\n\n" - end - - def print_error(error) - puts - print_border("#{INDENT}❌ Failure: #{error}: #{@test_name}") - end - - def print_success - print_border("#{INDENT}✅ Success: #{@test_name}") - end - - def print_output - puts "#{INDENT}-------------------------------------------------------------------" - print INDENT - print '🦀 ' - print @output.join.gsub("\n", "\n#{INDENT}") - end - - def finish(error) - print_output - - exit_code = if error - print_error(error) - false - else - print_success - true - end - - exit(exit_code) - end -end - -# Executes tests with console I/O. -class ConsoleTest < Test - def initialize(binary, qemu_cmd, test_name, console_subtests) - super() - - @binary = binary - @qemu_cmd = qemu_cmd - @test_name = test_name - @console_subtests = console_subtests - @cur_subtest = 1 - @output = ["Running #{@console_subtests.length} console-based tests\n", - "-------------------------------------------------------------------\n\n"] - end - - def format_test_name(number, name) - formatted_name = "#{number.to_s.rjust(3)}. #{name}" - formatted_name.ljust(63, '.') - end - - def run_subtest(subtest, qemu_out, qemu_in) - @output << format_test_name(@cur_subtest, subtest.name) - - subtest.run(qemu_out, qemu_in) - - @output << "[ok]\n" - @cur_subtest += 1 - end - - def exec - error = false - - PTY.spawn(@qemu_cmd) do |qemu_out, qemu_in| - begin - @console_subtests.each { |t| run_subtest(t, qemu_out, qemu_in) } - rescue StandardError => e - error = e.message - end - - finish(error) - end - end -end - -# A wrapper around the bare QEMU invocation. -class RawTest < Test - MAX_WAIT_SECS = 5 - - def initialize(binary, qemu_cmd, test_name) - super() - - @binary = binary - @qemu_cmd = qemu_cmd - @test_name = test_name - @output = [] - end - - def exec - error = 'Timed out waiting for test' - io = IO.popen(@qemu_cmd) - - while IO.select([io], nil, nil, MAX_WAIT_SECS) - begin - @output << io.read_nonblock(1024) - rescue EOFError - io.close - error = $CHILD_STATUS.to_i != 0 - break - end - end - - finish(error) - end -end - -##-------------------------------------------------------------------------------------------------- -## Script entry point -##-------------------------------------------------------------------------------------------------- -binary = ARGV.last -test_name = binary.gsub(%r{.*deps/}, '').split('-')[0] -console_test_file = "tests/#{test_name}.rb" -qemu_cmd = ARGV.join(' ') - -test_runner = if File.exist?(console_test_file) - load console_test_file - # subtest_collection is provided by console_test_file - ConsoleTest.new(binary, qemu_cmd, test_name, subtest_collection) - else - RawTest.new(binary, qemu_cmd, test_name) - end - -test_runner.exec diff --git a/14_exceptions_part2_peripheral_IRQs/.vscode/settings.json b/14_exceptions_part2_peripheral_IRQs/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/14_exceptions_part2_peripheral_IRQs/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/14_exceptions_part2_peripheral_IRQs/Cargo.lock b/14_exceptions_part2_peripheral_IRQs/Cargo.lock deleted file mode 100644 index 8930bc96d..000000000 --- a/14_exceptions_part2_peripheral_IRQs/Cargo.lock +++ /dev/null @@ -1,91 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "qemu-exit", - "register", - "test-macros", - "test-types", -] - -[[package]] -name = "proc-macro2" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "qemu-exit" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73ae13954572c7ca0ec48ba9fe6a59c0392066eba62f8cb384ffd5addf538c5" - -[[package]] -name = "quote" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "syn" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "443b4178719c5a851e1bde36ce12da21d74a0e60b4d982ec3385a933c812f0f6" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "test-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "test-types", -] - -[[package]] -name = "test-types" -version = "0.1.0" - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" - -[[package]] -name = "unicode-xid" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" diff --git a/14_exceptions_part2_peripheral_IRQs/Cargo.toml b/14_exceptions_part2_peripheral_IRQs/Cargo.toml deleted file mode 100644 index 5d57cf357..000000000 --- a/14_exceptions_part2_peripheral_IRQs/Cargo.toml +++ /dev/null @@ -1,55 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] -qemu-exit = "1.x.x" -test-types = { path = "test-types" } - -# Optional dependencies -register = { version = "1.x.x", features = ["no_std_unit_tests"], optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - -##-------------------------------------------------------------------------------------------------- -## Testing -##-------------------------------------------------------------------------------------------------- - -[dev-dependencies] -test-macros = { path = "test-macros" } - -# Unit tests are done in the library part of the kernel. -[lib] -name = "libkernel" -test = true - -# Disable unit tests for the kernel binary. -[[bin]] -name = "kernel" -test = false - -# List of tests without harness. -[[test]] -name = "00_console_sanity" -harness = false - -[[test]] -name = "02_exception_sync_page_fault" -harness = false diff --git a/14_exceptions_part2_peripheral_IRQs/Makefile b/14_exceptions_part2_peripheral_IRQs/Makefile deleted file mode 100644 index 58361af8a..000000000 --- a/14_exceptions_part2_peripheral_IRQs/Makefile +++ /dev/null @@ -1,177 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -# Testing-specific arguments -ifdef TEST - ifeq ($(TEST),unit) - TEST_ARG = --lib - else - TEST_ARG = --test $(TEST) - endif -endif - -QEMU_MISSING_STRING = "This board is not yet supported for QEMU." - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -FEATURES = bsp_$(BSP) -COMPILER_ARGS = --target=$(TARGET) \ - --features $(FEATURES) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -TEST_CMD = cargo test $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot -DOCKER_ARG_DEV = --privileged -v /dev:/dev -DOCKER_ARG_NET = --network host - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) - DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) - DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -else - DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu test chainboot jtagboot openocd gdb gdb-opt0 \ - clippy clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu test: - @echo $(QEMU_MISSING_STRING) -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) - -define KERNEL_TEST_RUNNER - #!/usr/bin/env bash - - $(OBJCOPY_CMD) $$1 $$1.img - TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') - $(DOCKER_TEST) ruby tests/runner.rb $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY -endef - -export KERNEL_TEST_RUNNER -test: - @mkdir -p target - @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh - @chmod +x target/kernel_test_runner.sh - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) -endif - -chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -jtagboot: - @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) - -openocd: - @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) - -define gen_gdb - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC) $1" $(RUSTC_CMD) - @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) -endef - -gdb: - $(call gen_gdb,-C debuginfo=2) - -gdb-opt0: - $(call gen_gdb,-C debuginfo=2 -C opt-level=0) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/14_exceptions_part2_peripheral_IRQs/README.md b/14_exceptions_part2_peripheral_IRQs/README.md deleted file mode 100644 index e983470be..000000000 --- a/14_exceptions_part2_peripheral_IRQs/README.md +++ /dev/null @@ -1,2793 +0,0 @@ -# Tutorial 14 - Exceptions Part 2: Peripheral IRQs - -## tl;dr - -- We write `device drivers` for the two interrupt controllers on the **Raspberry Pi 3** (Broadcom - custom controller) and **Pi 4** (ARM Generic Interrupt Controller v2, `GICv2`). -- Modularity is ensured by interfacing everything through a trait named `IRQManager`. -- Handling for our first peripheral IRQs is implemented: The `UART`'s receive IRQs. - -![Header](../doc/14_header.png) - -## Table of Contents - -- [Introduction](#introduction) -- [Different Controllers: A Usecase for Abstraction](#different-controllers-a-usecase-for-abstraction) -- [New Challenges: Reentrancy](#new-challenges-reentrancy) -- [Implementation](#implementation) - * [The Kernel's Interfaces for Interrupt Handling](#the-kernels-interfaces-for-interrupt-handling) - + [Uniquely Identifying an IRQ](#uniquely-identifying-an-irq) - - [The BCM IRQ Number Scheme](#the-bcm-irq-number-scheme) - - [The GICv2 IRQ Number Scheme](#the-gicv2-irq-number-scheme) - + [Registering IRQ Handlers](#registering-irq-handlers) - + [Handling Pending IRQs](#handling-pending-irqs) - * [Reentrancy: What to protect?](#reentrancy-what-to-protect) - * [The Interrupt Controller Device Drivers](#the-interrupt-controller-device-drivers) - + [The BCM Driver (Pi 3)](#the-bcm-driver-pi-3) - - [Peripheral Controller Register Access](#peripheral-controller-register-access) - - [The IRQ Handler Table](#the-irq-handler-table) - + [The GICv2 Driver (Pi 4)](#the-gicv2-driver-pi-4) - - [GICC Details](#gicc-details) - - [GICD Details](#gicd-details) -- [UART hack](#uart-hack) -- [Test it](#test-it) -- [Diff to previous](#diff-to-previous) - -## Introduction - -In [tutorial 12], we laid the groundwork for exception handling from the processor architecture -side. Handler stubs for the different exception types were set up, and a first glimpse at exception -handling was presented by causing a `synchronous` exception by means of a `page fault`. - -[tutorial 12]: ../12_exceptions_part1_groundwork - -In this tutorial, we will add a first level of support for one of the three types of `asynchronous` -exceptions that are defined for `AArch64`: `IRQs`. The overall goal for this tutorial is to get rid -of the busy-loop at the end of our current `kernel_main()` function, which actively polls the -`UART` for newly received characters. Instead, we will let the processor idle and wait for the -`UART`'s RX IRQs, which indicate that new characters were received. A respective `IRQ` service -routine, provided by the `UART` driver, will run in response to the `IRQ` and print the characters. - -## Different Controllers: A Usecase for Abstraction - -One very exciting aspect of this tutorial is that the `Pi 3` and the `Pi 4` feature completely -different interrupt controllers. This is also a first in all of the tutorial series. Until now, both -Raspberrys did not need differentiation with respect to their devices. - -The `Pi 3` has a very simple custom controller made by Broadcom (BCM), the manufacturer of the Pi's -`System-on-Chip`. The `Pi 4` features an implementation of `ARM`'s Generic Interrupt Controller -version 2 (`GICv2`). Since ARM's GIC controllers are the prevalent interrupt controllers in ARM -application procesors, it is very beneficial to finally have it on the Raspberry Pi. It will enable -people to learn about one of the most common building blocks in ARM-based embedded computing. - -This also means that we can finally make full use of all the infrastructure for abstraction that we -prepared already. We will design an `IRQManager` interface trait and implement it in both controller -drivers. The generic part of our `kernel` code will only be exposed to this trait (compare to the -diagram in the [tl;dr] section). This common idiom of *program to an interface, not an -implementation* enables a clean abstraction and makes the code modular and pluggable. - -[tl;dr]: #tldr - -## New Challenges: Reentrancy - -Enabling interrupts also poses new challenges with respect to protecting certain code sections in -the kernel from being [re-entered]. Please read the linked article for background on that topic. - -[re-entered]: https://en.wikipedia.org/wiki/Reentrancy_(computing) - -Our `kernel` is still running on a single core. For this reason, we are still using our `NullLock` -pseudo-locks for `Critical Sections` or `shared resources`, instead of real `Spinlocks`. Hence, -interrupt handling at this point in time does not put us at risk of running into one of those -dreaded `deadlocks`, which is one of several side-effects that reentrancy can cause. For example, a -`deadlock` because of interrupts can happen happen when the executing CPU core has locked a -`Spinlock` at the beginning of a function, an IRQ happens, and the IRQ service routine is trying to -execute the same function. Since the lock is already locked, the core would spin forever waiting for -it to be released. - -There is no straight-forward way to tell if a function is `reentrantcy`-safe or not. It usually -needs careful manual checking to conclude. Even though it might be technically safe to `re-enter` a -function, sometimes you don't want that to happen for functional reasons. For example, printing of a -string should not be interrupted by a an interrupt service routine that starts printing another -string, so that the output mixes. In the course of this tutorial, we will check and see where we -want to protect against `reentrancy`. - -## Implementation - -Okay, let's start. The following sections cover the the implementation in a top-down fashion, -starting with the trait that interfaces all the `kernel` components to each other. - -### The Kernel's Interfaces for Interrupt Handling - -First, we design the `IRQManager` trait that interrupt controller drivers must implement. The -minimal set of functionality that we need for starters is: - -1. Registering an IRQ `handler` for a given IRQ `number`. -2. Enabling an IRQ (from the controller side). -3. Handling pending IRQs. -4. Printing the list of registered IRQ handlers. - -The trait is defined as `exception::asynchronous::interface::IRQManager`: - -```rust -pub trait IRQManager { - /// The IRQ number type depends on the implementation. - type IRQNumberType; - - /// Register a handler. - fn register_handler( - &self, - irq_number: Self::IRQNumberType, - descriptor: super::IRQDescriptor, - ) -> Result<(), &'static str>; - - /// Enable an interrupt in the controller. - fn enable(&self, irq_number: Self::IRQNumberType); - - /// Handle pending interrupts. - /// - /// This function is called directly from the CPU's IRQ exception vector. On AArch64, - /// this means that the respective CPU core has disabled exception handling. - /// This function can therefore not be preempted and runs start to finish. - /// - /// Takes an IRQContext token to ensure it can only be called from IRQ context. - #[allow(clippy::trivially_copy_pass_by_ref)] - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - ic: &super::IRQContext<'irq_context>, - ); - - /// Print list of registered handlers. - fn print_handler(&self); -} -``` - -#### Uniquely Identifying an IRQ - -The first member of the trait is the [associated type] `IRQNumberType`. The following explains why -we make it customizable for the implementor and do not define the type as a plain integer right -away. - -Interrupts can generally be characterizied with the following properties: - -[associated type]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types - -1. Software-generated vs hardware-generated. -2. Private vs shared. - -Different interrupt controllers take different approaches at categorizing and numbering IRQs that -have one or the other property. Often times, this leads to situations where a plain integer does not -suffice to uniquely identify an IRQ, and makes it necessary to encode additional information in the -used type. Letting the respective interrupt controller driver define `IRQManager::IRQNumberType` -itself addresses this issue. The rest of the `BSP` must then conditionally use this type. - -##### The BCM IRQ Number Scheme - -The `BCM` controller of the `Raspberry Pi 3`, for example, is composed of two functional parts: A -**local** controller and a **peripheral** controller. The BCM's **local controller** handles all -`private` IRQs, which means private SW-generated IRQs and IRQs of private HW devices. An example for -the latter would be the `ARMv8` timer. Each CPU core has its own private instance of it. The BCM's -**peripheral controller** handles all IRQs of `non-private` HW devices such as the `UART` (if those -IRQs can be declared as `shared` according to our taxonomy above is a different discussion, because -the BCM controller allows these HW interrupts to be routed to _only one CPU core at a time_). - -The IRQ numbers of the BCM **local controller** range from `0..11`. The numbers of the **peripheral -controller** range from `0..63`. This demonstrates why a primitive integer type would not be -sufficient to uniquely encode the IRQs, because their ranges overlap. In the driver for the `BCM` -controller, we therefore define the associated type as follows: - -```rust -pub type LocalIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -pub type PeripheralIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; - -/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -#[derive(Copy, Clone)] -pub enum IRQNumber { - Local(LocalIRQ), - Peripheral(PeripheralIRQ), -} -``` - -The type `exception::asynchronous::IRQNumber` is a newtype around an `usize` that uses a [const -generic] to ensure that the value of the encapsulated IRQ number is in the allowed range (e.g. -`0..MAX_LOCAL_IRQ_NUMBER` for `LocalIRQ`, with `MAX_LOCAL_IRQ_NUMBER == 11`). - -[const generic]: https://github.com/rust-lang/rfcs/blob/master/text/2000-const-generics.md - -##### The GICv2 IRQ Number Scheme - -The `GICv2` in the `Raspberry Pi 4`, on the other hand, uses a different scheme. IRQ numbers `0..31` -are for `private` IRQs. Those are further subdivided into `SW-generated` (SGIs, `0..15`) and -`HW-generated` (PPIs, Private Peripheral Interrupts, `16..31`). Numbers `32..1019` are for `shared -hardware-generated` interrupts (SPI, Shared Peripheral Interrupts). - -There are no overlaps, so this scheme enables us to actually have a plain integer as a unique -identifier for the IRQs. We define the type as follows: - -```rust -/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; -``` - -#### Registering IRQ Handlers - -To enable the controller driver to manage interrupt handling, it must know where to find respective -handlers, and it must know how to call them. For the latter, we define an `IRQHandler` trait in -`exception::asynchronous` that must be implemented by any SW entity that wants to handle IRQs: - -```rust -/// Implemented by types that handle IRQs. -pub trait IRQHandler { - /// Called when the corresponding interrupt is asserted. - fn handle(&self) -> Result<(), &'static str>; -} -``` - -The `PL011Uart` driver gets the honors for being our first driver to ever implement this trait. In -this tutorial, the `RX IRQ` and the `RX Timeout IRQ` will be configured. This means that the -`PL011Uart` will assert it's interrupt line when one of following conditions is met: - -1. `RX IRQ`: The RX FIFO fill level is equal or more than the configured trigger level (which will be 1/8 of - the total FIFO size in our case). -1. `RX Timeout IRQ`: The RX FIFO fill level is greater than zero, but less than the configured fill - level, and the characters have not been pulled for a certain amount of time. The exact time is - not documented in the respective `PL011Uart` datasheet. Usually, it is a single-digit multiple of - the time it takes to receive or transmit one character on the serial line. - - In the handler, our standard scheme of echoing any received characters back to the host is used: - -```rust -impl exception::asynchronous::interface::IRQHandler for PL011Uart { - fn handle(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| { - let pending = inner.registers.MIS.extract(); - - // Clear all pending IRQs. - inner.registers.ICR.write(ICR::ALL::CLEAR); - - // Check for any kind of RX interrupt. - if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { - // Echo any received characters. - while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { - inner.write_char(c) - } - } - }); - - Ok(()) - } -} -``` - -Registering and enabling handlers in the interrupt controller is supposed to be done by the -respective drivers themselves. Therefore, we added a new function to the standard device driver -trait in `driver::interface::DeviceDriver` that must be implemented if IRQ handling is supported: - -```rust -/// Called by the kernel to register and enable the device's IRQ handlers, if any. -/// -/// Rust's type system will prevent a call to this function unless the calling instance -/// itself has static lifetime. -fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { - Ok(()) -} -``` - -Here is the implementation for the `PL011Uart`: - -```rust -fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { - use bsp::exception::asynchronous::irq_manager; - use exception::asynchronous::{interface::IRQManager, IRQDescriptor}; - - let descriptor = IRQDescriptor { - name: "BCM PL011 UART", - handler: self, - }; - - irq_manager().register_handler(self.irq_number, descriptor)?; - irq_manager().enable(self.irq_number); - - Ok(()) -} -``` - -The `bsp::exception::asynchronous::irq_manager()` function used here returns a reference to an -implementor of the `IRQManager` trait. Since the implementation is supposed to be done by the -platform's interrupt controller, this call will redirect to the `kernel`'s instance of either the -driver for the `BCM` controller (`Raspberry Pi 3`) or the driver for the `GICv2` (`Pi 4`). We will -look into the implementation of the `register_handler()` function from the driver's perspective -later. The gist here is that the calls on `irq_manager()` will make the platform's interrupt -controller aware that the `UART` driver (i) wants to handle its interrupt and (ii) which function it -provides to do so. - -Also note how `irq_number` is a member of the `PL011Uart` struct and not hardcoded. The reason is -that the `UART` driver code is agnostic about the **IRQ numbers** that are associated to it. This is -vendor-supplied information and as such typically part of the Board Support Package (`BSP`). It can -vary from `BSP` to `BSP`, same like the board's memory map, which provides the `UART`'s MMIO -register addresses. Therefore, we extend the instantiation of the `UART` driver accordingly, so that -the `BSP` now additionally provides the IRQ number as an argument: - -```rust -static PL011_UART: device_driver::PL011Uart = unsafe { - device_driver::PL011Uart::new( - memory::map::mmio::PL011_UART_BASE, - exception::asynchronous::irq_map::PL011_UART, - ) -}; -``` - -With all this in place, we can finally let drivers register and enable their IRQ handlers with the -interrupt controller, and unmask IRQ reception on the boot CPU core during the kernel init phase in -`main.rs`. After unmasking, IRQ handling is live: - -```rust -// Let device drivers register and enable their handlers with the interrupt controller. -for i in bsp::driver::driver_manager().all_device_drivers() { - if let Err(msg) = i.register_and_enable_irq_handler() { - warn!("Error registering IRQ handler: {}", msg); - } -} - -// Unmask interrupts on the boot CPU core. -exception::asynchronous::local_irq_unmask(); -``` - -#### Handling Pending IRQs - -Now that interrupts can happen, the `kernel` needs a way of requesting the interrupt controller -driver to handle pending interrupts. Therefore, implementors of the trait `IRQManager` must also -supply the following function: - -```rust -fn handle_pending_irqs<'irq_context>( - &'irq_context self, - ic: &super::IRQContext<'irq_context>, -); -``` - -An important aspect of this function signature is that we want to ensure that IRQ handling is only -possible from IRQ context. Part of the reason is that this invariant allows us to make some implicit -assumptions (which might depend on the target architecture, though). For example, as we have learned -in [tutorial 12], in `AArch64`, _"all kinds of exceptions are turned off upon taking an exception, -so that by default, exception handlers can not get interrupted themselves"_ (note that an IRQ is an -exception). This is a useful property that relieves us from explicitly protecting IRQ handling from -being interrupted itself. Another reason would be that calling IRQ handling functions from arbitrary -execution contexts just doesn't make a lot of sense. - -[tutorial 12]: ../12_exceptions_part1_groundwork/ - -So in order to ensure that this function is only being called from IRQ context, we borrow a -technique that I first saw in the [Rust embedded WG]'s [bare-metal crate]. It uses Rust's type -system to create a "token" that is only valid for the duration of the IRQ context. We create it -directly at the top of the IRQ vector function in `_arch/aarch64/exception.rs`, and pass it on to -the the implementation of the trait's handling function: - -[Rust embedded WG]: https://github.com/rust-embedded/bare-metal -[bare-metal crate]: https://github.com/rust-embedded/bare-metal/blob/master/src/lib.rs#L20 - -```rust -#[no_mangle] -unsafe extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { - use exception::asynchronous::interface::IRQManager; - - let token = &exception::asynchronous::IRQContext::new(); - bsp::exception::asynchronous::irq_manager().handle_pending_irqs(token); -} -``` - -By requiring the caller of the function `handle_pending_irqs()` to provide this `IRQContext` token, -we can prevent that the same function is accidentally being called from somewhere else. It is -evident, though, that for this to work, it is the _user's responsibility_ to only ever create this -token from within an IRQ context. If you want to circumvent this on purpose, you can do it. - -### Reentrancy: What to protect? - -Now that interrupt handling is live, we need to think about `reentrancy`. At [the beginning of this -tutorial], we mused about the need to protect certain functions from being re-entered, and that it -is not straight-forward to identify all the places that need protection. - -[the beginning of this tutorial]: #new-challenges-reentrancy - -In this tutorial, we will keep this part short nonetheless by taking a better-safe-than-sorry -approach. In the past, we already made efforts to prepare parts of `shared resources` (e.g. global -device driver instances) to be protected against parallel access. We did so by wrapping them into -`NullLocks`, which we will upgrade to real `Spinlocks` once we boot secondary CPU cores. - -We can hook on that previous work and reason that anything that we wanted protected against parallel -access so far, we also want it protected against reentrancy now. Therefore, we upgrade all -`NullLocks` to `IRQSafeNullocks`: - -```rust -impl interface::Mutex for IRQSafeNullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - // Execute the closure while IRQs are masked. - exception::asynchronous::exec_with_irq_masked(|| f(data)) - } -} -``` - -The new part is that the call to `f(data)` is executed as a closure in -`exception::asynchronous::exec_with_irq_masked()`. Inside that function, IRQs on the executing CPU -core are masked before the `f(data)` is being executed, and restored afterwards: - -```rust -/// Executes the provided closure while IRQs are masked on the executing core. -/// -/// While the function temporarily changes the HW state of the executing core, it restores it to the -/// previous state before returning, so this is deemed safe. -#[inline(always)] -pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { - let ret: T; - - unsafe { - let saved = local_irq_mask_save(); - ret = f(); - local_irq_restore(saved); - } - - ret -} -``` - -The helper functions used here are defined in `src/_arch/aarch64/exception/asynchronous.rs`. - -### The Interrupt Controller Device Drivers - -The previous sections explained how the `kernel` uses the `IRQManager` trait. Now, let's have a look -at the driver-side of it in the Raspberry Pi `BSP`. We start with the Broadcom interrupt controller -featured in the `Pi 3`. - -#### The BCM Driver (Pi 3) - -As mentioned earlier, the `BCM` driver consists of two subcomponents, a **local** and a -**peripheral** controller. The local controller owns a bunch of configuration registers, among -others, the `routing` configuration for peripheral IRQs such as those from the `UART`. Peripheral -IRQs can be routed to _one core only_. In our case, we leave the default unchanged, which means -everything is routed to the boot CPU core. The image below depicts the `struct diagram` of the -driver implementation. - -![BCM Driver](../doc/14_BCM_driver.png) - -We have a top-level driver, which implements the `IRQManager` trait. _Only the top-level driver_ is -exposed to the rest of the `kernel`. The top-level itself has two members, representing the local -and the peripheral controller, respectively, which implement the `IRQManager` trait as well. This -design allows for easy forwarding of function calls from the top-level driver to one of the -subcontrollers. - -For this tutorial, we leave out implementation of the local controller, because we will only be -concerned with the peripheral `UART` IRQ. - -##### Peripheral Controller Register Access - -When writing a device driver for a kernel with exception handling and multi-core support, it is -always important to analyze what parts of the driver will need protection against reentrancy (we -talked about this earlier in this tutorial) and/or parallel execution of other driver parts. If a -driver function needs to follow a vendor-defined sequence of multiple register operations that -include `write operations`, this is usually a good hint that protection might be needed. But that is -only one of many examples. - -For the driver implementation in this tutorial, we are following a simple rule: Register read access -is deemed always safe. Write access is guarded by an `IRQSafeNullLock`, which means that we are safe -against `reentrancy` issues, and also in the future when the kernel will be running on multiple -cores, we can easily upgrade to a real spinlock, which serializes register write operations from -different CPU cores. - -In fact, for this tutorial, we probably would not have needed any protection yet, because all the -driver does is read from the `PENDING_*` registers for the `handle_pending_irqs()` implementation, -and writing to the `ENABLE_*` registers for the `enable()` implementation. However, the chosen -architecture will have us set up for future extensions, when more complex register manipulation -sequences might be needed. - -Since nothing complex is happening in the implementation, it is not covered in detail here. Please -refer to [the source of the **peripheral** controller] to check it out. - -[the source of the **peripheral** controller]: src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs - -##### The IRQ Handler Table - -Calls to `register_handler()` result in the driver inserting the provided handler reference in a -specific table (the handler reference is a member of `IRQDescriptor`): - -```rust -type HandlerTable = - [Option; InterruptController::NUM_PERIPHERAL_IRQS]; -``` - -One of the requirements for safe operation of the `kernel` is that those handlers are not -registered, removed or exchanged in the middle of an IRQ handling situation. This, again, is a -multi-core scenario where one core might look up a handler entry while another core is modifying the -same in parallel. - -While we want to allow drivers to take the decision of registering or not registering a handler at -runtime, there is no need to allow it for the _whole_ runtime of the kernel. It is fine to restrict -this option to the kernel `init phase`, at which only a single boot core runs and IRQs are masked. - -We introduce the so called `InitStateLock` for cases like that. From an API-perspective, it is a -special variant of a `Read/Write exclusion synchronization primitive`. RWLocks in the Rust standard -library [are characterized] as allowing _"a number of readers or at most one writer at any point in -time"_. For the `InitStateLock`, we only implement the `read()` and `write()` functions: - -[are characterized]: https://doc.rust-lang.org/std/sync/struct.RwLock.html - -```rust -impl interface::ReadWriteEx for InitStateLock { - type Data = T; - - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - assert!( - state::state_manager().is_init(), - "InitStateLock::write called after kernel init phase" - ); - assert!( - !exception::asynchronous::is_local_irq_masked(), - "InitStateLock::write called with IRQs unmasked" - ); - - let data = unsafe { &mut *self.data.get() }; - - f(data) - } - - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { - let data = unsafe { &*self.data.get() }; - - f(data) - } -} -``` - -The `write()` function is guarded by two `assertions`. One ensures that IRQs are masked, the other -checks the `state::state_manager()` if the kernel is still in the init phase. The `State Manager` is -new since this tutorial, and implemented in `src/state.rs`. It provides atomic state transition and -reporting functions that are called when the kernel enters a new phase. In the current kernel, the -only call is happening before the transition from `kernel_init()` to `kernel_main()`: - -```rust -// Announce conclusion of the kernel_init() phase. -state::state_manager().transition_to_single_core_main(); -``` - -#### The GICv2 Driver (Pi 4) - -As we learned earlier, the ARM `GICv2` in the `Raspberry Pi 4` features a continuous interrupt -number range: -- IRQ numbers `0..31` represent IRQs that are private (aka local) to the respective processor core. -- IRQ numbers `32..1019` are for shared IRQs. - -The `GIC` has a so-called `Distributor`, the `GICD`, and a `CPU Interface`, the `GICC`. The `GICD`, -among other things, is used to enable IRQs and route them to one or more CPU cores. The `GICC` is -used by CPU cores to check which IRQs are pending, and to acknowledge them once they were handled. -There is one dedicated `GICC` for _each CPU core_. - -One neat thing about the `GICv2` is that any MMIO registers that are associated to core-private IRQs -are `banked`. That means that different CPU cores can assert the same MMIO address, but they will -end up accessing a core-private copy of the referenced register. This makes it very comfortable to -program the `GIC`, because this hardware design ensures that each core only ever gets access to its -own resources. Preventing one core to accidentally or willfully fiddle with the IRQ state of another -core must therefore not be enforced in software. - -In summary, this means that any registers in the `GICD` that deal with the core-private IRQ range -are banked. Since there is one `GICC` per CPU core, the whole thing is banked. This allows us to -design the following `struct diagram` for our driver implementation: - -![GICv2 Driver](../doc/14_GICv2_driver.png) - -The top-level struct is composed of a `GICD`, a `GICC` and a `HandlerTable`. The latter is -implemented identically as in the `Pi 3`. - -##### GICC Details - -Since the `GICC` is banked wholly, the top-level driver can directly forward any requests to it, -without worrying about concurrency issues for now. Note that this only works as long as the `GICC` -implementation is only accessing the banked `GICC` registers, and does not save any state in member -variables that are stored in `DRAM`. The two main duties of the `GICC` struct are to read the `IAR` -(Interrupt Acknowledge) register, which returns the number of the highest-priority pending IRQ, and -writing to the `EOIR` (End Of Interrupt) register, which tells the hardware that handling of an -interrupt is now concluded. - -##### GICD Details - -The `GICD` hardware block differentiates between `shared` and `banked` registers. As with the -`GICC`, we don't have to protect the banked registers against concurrent access. The shared -registers are wrapped into an `IRQSafeNullLock` again. The important parts of the `GICD` for this -tutorial are the `ITARGETSR[256]` and `ISENABLER[32]` register arrays. - -Each `ITARGETSR` is subdivided into four _bytes_. Each byte represents one IRQ, and stores a bitmask -that encodes all the `GICCs` to which the respective IRQ is forwarded. For example, -`ITARGETSR[0].byte0` would represent IRQ number 0, and `ITARGETSR[0].byte3` IRQ number 3. In the -`ISENABLER`, each _bit_ represents an IRQ. For example, `ISENABLER[0].bit3` is IRQ number 3. - -In summary, this means that `ITARGETSR[0..7]` and `ISENABLER[0]` represent the first 32 IRQs (the -banked ones), and as such, we split the register block into `shared` and `banked` parts accordingly -in `gicd.rs`: - -```rust -register_structs! { - #[allow(non_snake_case)] - SharedRegisterBlock { - (0x000 => CTLR: ReadWrite), - (0x004 => TYPER: ReadOnly), - (0x008 => _reserved1), - (0x104 => ISENABLER: [ReadWrite; 31]), - (0x108 => _reserved2), - (0x820 => ITARGETSR: [ReadWrite; 248]), - (0x824 => @END), - } -} - -register_structs! { - #[allow(non_snake_case)] - BankedRegisterBlock { - (0x000 => _reserved1), - (0x100 => ISENABLER: ReadWrite), - (0x104 => _reserved2), - (0x800 => ITARGETSR: [ReadOnly; 8]), - (0x804 => @END), - } -} -``` - -As with the implementation of the BCM interrupt controller driver, we won't cover the remaining -parts in exhaustive detail. For that, please refer to [this folder] folder which contains all the -sources. - -[this folder]: src/bsp/device_driver/arm - -## Test it - -When you load the kernel, any keystroke results in echoing back the character by way of IRQ -handling. There is no more polling done at the end of `kernel_main()`, just waiting for events such -as IRQs: - -```rust -fn kernel_main() -> ! { - - // omitted for brevity - - info!("Echoing input now"); - cpu::wait_forever(); -} -``` - -Raspberry Pi 3: - -```console -$ make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 3 - -[ML] Requesting binary -[MP] ⏩ Pushing 66 KiB ========================================🦀 100% 33 KiB/s Time: 00:00:02 -[ML] Loaded! Executing the payload now - -[ 3.134937] Booting on: Raspberry Pi 3 -[ 3.136023] MMU online. Special regions: -[ 3.137934] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data -[ 3.142017] 0x3f000000 - 0x4000ffff | 16 MiB | Dev RW PXN | Device MMIO -[ 3.145579] Current privilege level: EL1 -[ 3.147490] Exception handling state: -[ 3.149271] Debug: Masked -[ 3.150835] SError: Masked -[ 3.152398] IRQ: Unmasked -[ 3.154049] FIQ: Masked -[ 3.155613] Architectural timer resolution: 52 ns -[ 3.157915] Drivers loaded: -[ 3.159262] 1. BCM GPIO -[ 3.160695] 2. BCM PL011 UART -[ 3.162389] 3. BCM Interrupt Controller -[ 3.164518] Registered IRQ handlers: -[ 3.166255] Peripheral handler: -[ 3.168038] 57. BCM PL011 UART -[ 3.170078] Echoing input now -``` - -Raspberry Pi 4: - -```console -$ BSP=rpi4 make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 4 - -[ML] Requesting binary -[MP] ⏩ Pushing 73 KiB ========================================🦀 100% 24 KiB/s Time: 00:00:03 -[ML] Loaded! Executing the payload now - -[ 3.413865] Booting on: Raspberry Pi 4 -[ 3.414255] MMU online. Special regions: -[ 3.416166] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data -[ 3.420249] 0xfe000000 - 0xff84ffff | 24 MiB | Dev RW PXN | Device MMIO -[ 3.423811] Current privilege level: EL1 -[ 3.425722] Exception handling state: -[ 3.427503] Debug: Masked -[ 3.429067] SError: Masked -[ 3.430630] IRQ: Unmasked -[ 3.432281] FIQ: Masked -[ 3.433845] Architectural timer resolution: 18 ns -[ 3.436147] Drivers loaded: -[ 3.437494] 1. BCM GPIO -[ 3.438927] 2. BCM PL011 UART -[ 3.440621] 3. GICv2 (ARM Generic Interrupt Controller v2) -[ 3.443575] Registered IRQ handlers: -[ 3.445312] Peripheral handler: -[ 3.447096] 153. BCM PL011 UART -[ 3.449136] Echoing input now -``` - -## Diff to previous -```diff - -diff -uNr 13_integrated_testing/Makefile 14_exceptions_part2_peripheral_IRQs/Makefile ---- 13_integrated_testing/Makefile -+++ 14_exceptions_part2_peripheral_IRQs/Makefile -@@ -57,8 +57,9 @@ - RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) - RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -+FEATURES = bsp_$(BSP) - COMPILER_ARGS = --target=$(TARGET) \ -- --features bsp_$(BSP) \ -+ --features $(FEATURES) \ - --release - - RUSTC_CMD = cargo rustc $(COMPILER_ARGS) - -diff -uNr 13_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs ---- 13_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs -@@ -10,6 +10,10 @@ - // Private Definitions - //-------------------------------------------------------------------------------------------------- - -+mod daif_bits { -+ pub const IRQ: u8 = 0b0010; -+} -+ - trait DaifField { - fn daif_field() -> register::Field; - } -@@ -58,6 +62,71 @@ - // Public Code - //-------------------------------------------------------------------------------------------------- - -+/// Returns whether IRQs are masked on the executing core. -+pub fn is_local_irq_masked() -> bool { -+ !is_masked::() -+} -+ -+/// Unmask IRQs on the executing core. -+/// -+/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. -+/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: -+/// -+/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional -+/// synchronization." -+/// -+/// # Safety -+/// -+/// - Changes the HW state of the executing core. -+#[inline(always)] -+pub unsafe fn local_irq_unmask() { -+ #[rustfmt::skip] -+ asm!( -+ "msr DAIFClr, {arg}", -+ arg = const daif_bits::IRQ, -+ options(nomem, nostack, preserves_flags) -+ ); -+} -+ -+/// Mask IRQs on the executing core. -+/// -+/// # Safety -+/// -+/// - Changes the HW state of the executing core. -+#[inline(always)] -+pub unsafe fn local_irq_mask() { -+ #[rustfmt::skip] -+ asm!( -+ "msr DAIFSet, {arg}", -+ arg = const daif_bits::IRQ, -+ options(nomem, nostack, preserves_flags) -+ ); -+} -+ -+/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). -+/// -+/// # Safety -+/// -+/// - Changes the HW state of the executing core. -+#[inline(always)] -+pub unsafe fn local_irq_mask_save() -> u64 { -+ let saved = DAIF.get(); -+ local_irq_mask(); -+ -+ saved -+} -+ -+/// Restore the interrupt mask bits (DAIF) using the callee's argument. -+/// -+/// # Safety -+/// -+/// - Changes the HW state of the executing core. -+/// - No sanity checks on the input. -+#[inline(always)] -+pub unsafe fn local_irq_restore(saved: u64) { -+ DAIF.set(saved); -+} -+ - /// Print the AArch64 exceptions status. - #[rustfmt::skip] - pub fn print_state() { - -diff -uNr 13_integrated_testing/src/_arch/aarch64/exception.rs 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs ---- 13_integrated_testing/src/_arch/aarch64/exception.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs -@@ -4,6 +4,7 @@ - - //! Architectural synchronous and asynchronous exception handling. - -+use crate::{bsp, exception}; - use core::{cell::UnsafeCell, fmt}; - use cortex_a::{barrier, regs::*}; - use register::InMemoryRegister; -@@ -84,8 +85,11 @@ - } - - #[no_mangle] --unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { -- default_exception_handler(e); -+unsafe extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { -+ use exception::asynchronous::interface::IRQManager; -+ -+ let token = &exception::asynchronous::IRQContext::new(); -+ bsp::exception::asynchronous::irq_manager().handle_pending_irqs(token); - } - - #[no_mangle] - -diff -uNr 13_integrated_testing/src/bsp/device_driver/arm/gicv2/gicc.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs ---- 13_integrated_testing/src/bsp/device_driver/arm/gicv2/gicc.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs -@@ -0,0 +1,137 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! GICC Driver - GIC CPU interface. -+ -+use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; -+use register::{mmio::*, register_bitfields, register_structs}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+register_bitfields! { -+ u32, -+ -+ /// CPU Interface Control Register -+ CTLR [ -+ Enable OFFSET(0) NUMBITS(1) [] -+ ], -+ -+ /// Interrupt Priority Mask Register -+ PMR [ -+ Priority OFFSET(0) NUMBITS(8) [] -+ ], -+ -+ /// Interrupt Acknowledge Register -+ IAR [ -+ InterruptID OFFSET(0) NUMBITS(10) [] -+ ], -+ -+ /// End of Interrupt Register -+ EOIR [ -+ EOIINTID OFFSET(0) NUMBITS(10) [] -+ ] -+} -+ -+register_structs! { -+ #[allow(non_snake_case)] -+ pub RegisterBlock { -+ (0x000 => CTLR: ReadWrite), -+ (0x004 => PMR: ReadWrite), -+ (0x008 => _reserved1), -+ (0x00C => IAR: ReadWrite), -+ (0x010 => EOIR: ReadWrite), -+ (0x014 => @END), -+ } -+} -+ -+/// Abstraction for the associated MMIO registers. -+type Registers = MMIODerefWrapper; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Representation of the GIC CPU interface. -+pub struct GICC { -+ registers: Registers, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl GICC { -+ /// Create an instance. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ Self { -+ registers: Registers::new(mmio_start_addr), -+ } -+ } -+ -+ /// Accept interrupts of any priority. -+ /// -+ /// Quoting the GICv2 Architecture Specification: -+ /// -+ /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field -+ /// value." -+ /// -+ /// # Safety -+ /// -+ /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead -+ /// of `&mut self`. -+ pub fn priority_accept_all(&self) { -+ self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. -+ } -+ -+ /// Enable the interface - start accepting IRQs. -+ /// -+ /// # Safety -+ /// -+ /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead -+ /// of `&mut self`. -+ pub fn enable(&self) { -+ self.registers.CTLR.write(CTLR::Enable::SET); -+ } -+ -+ /// Extract the number of the highest-priority pending IRQ. -+ /// -+ /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. -+ /// -+ /// # Safety -+ /// -+ /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead -+ /// of `&mut self`. -+ #[allow(clippy::trivially_copy_pass_by_ref)] -+ pub fn pending_irq_number<'irq_context>( -+ &self, -+ _ic: &exception::asynchronous::IRQContext<'irq_context>, -+ ) -> usize { -+ self.registers.IAR.read(IAR::InterruptID) as usize -+ } -+ -+ /// Complete handling of the currently active IRQ. -+ /// -+ /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. -+ /// -+ /// To be called after `pending_irq_number()`. -+ /// -+ /// # Safety -+ /// -+ /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead -+ /// of `&mut self`. -+ #[allow(clippy::trivially_copy_pass_by_ref)] -+ pub fn mark_comleted<'irq_context>( -+ &self, -+ irq_number: u32, -+ _ic: &exception::asynchronous::IRQContext<'irq_context>, -+ ) { -+ self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); -+ } -+} - -diff -uNr 13_integrated_testing/src/bsp/device_driver/arm/gicv2/gicd.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs ---- 13_integrated_testing/src/bsp/device_driver/arm/gicv2/gicd.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs -@@ -0,0 +1,195 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! GICD Driver - GIC Distributor. -+//! -+//! # Glossary -+//! - SPI - Shared Peripheral Interrupt. -+ -+use crate::{ -+ bsp::device_driver::common::MMIODerefWrapper, state, synchronization, -+ synchronization::IRQSafeNullLock, -+}; -+use register::{mmio::*, register_bitfields, register_structs}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+register_bitfields! { -+ u32, -+ -+ /// Distributor Control Register -+ CTLR [ -+ Enable OFFSET(0) NUMBITS(1) [] -+ ], -+ -+ /// Interrupt Controller Type Register -+ TYPER [ -+ ITLinesNumber OFFSET(0) NUMBITS(5) [] -+ ], -+ -+ /// Interrupt Processor Targets Registers -+ ITARGETSR [ -+ Offset3 OFFSET(24) NUMBITS(8) [], -+ Offset2 OFFSET(16) NUMBITS(8) [], -+ Offset1 OFFSET(8) NUMBITS(8) [], -+ Offset0 OFFSET(0) NUMBITS(8) [] -+ ] -+} -+ -+register_structs! { -+ #[allow(non_snake_case)] -+ SharedRegisterBlock { -+ (0x000 => CTLR: ReadWrite), -+ (0x004 => TYPER: ReadOnly), -+ (0x008 => _reserved1), -+ (0x104 => ISENABLER: [ReadWrite; 31]), -+ (0x108 => _reserved2), -+ (0x820 => ITARGETSR: [ReadWrite; 248]), -+ (0x824 => @END), -+ } -+} -+ -+register_structs! { -+ #[allow(non_snake_case)] -+ BankedRegisterBlock { -+ (0x000 => _reserved1), -+ (0x100 => ISENABLER: ReadWrite), -+ (0x104 => _reserved2), -+ (0x800 => ITARGETSR: [ReadOnly; 8]), -+ (0x804 => @END), -+ } -+} -+ -+/// Abstraction for the non-banked parts of the associated MMIO registers. -+type SharedRegisters = MMIODerefWrapper; -+ -+/// Abstraction for the banked parts of the associated MMIO registers. -+type BankedRegisters = MMIODerefWrapper; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Representation of the GIC Distributor. -+pub struct GICD { -+ /// Access to shared registers is guarded with a lock. -+ shared_registers: IRQSafeNullLock, -+ -+ /// Access to banked registers is unguarded. -+ banked_registers: BankedRegisters, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl SharedRegisters { -+ /// Return the number of IRQs that this HW implements. -+ #[inline(always)] -+ fn num_irqs(&mut self) -> usize { -+ // Query number of implemented IRQs. -+ // -+ // Refer to GICv2 Architecture Specification, Section 4.3.2. -+ ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 -+ } -+ -+ /// Return a slice of the implemented ITARGETSR. -+ #[inline(always)] -+ fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { -+ assert!(self.num_irqs() >= 36); -+ -+ // Calculate the max index of the shared ITARGETSR array. -+ // -+ // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS -+ // register has four entries, so shift right by two. Subtract one because we start -+ // counting at zero. -+ let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; -+ -+ // Rust automatically inserts slice range sanity check, i.e. max >= min. -+ &self.ITARGETSR[0..spi_itargetsr_max_index] -+ } -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+use synchronization::interface::Mutex; -+ -+impl GICD { -+ /// Create an instance. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ Self { -+ shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), -+ banked_registers: BankedRegisters::new(mmio_start_addr), -+ } -+ } -+ -+ /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. -+ /// -+ /// Quoting the GICv2 Architecture Specification: -+ /// -+ /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that -+ /// corresponds only to the processor reading the register." -+ fn local_gic_target_mask(&self) -> u32 { -+ self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) -+ } -+ -+ /// Route all SPIs to the boot core and enable the distributor. -+ pub fn boot_core_init(&self) { -+ assert!( -+ state::state_manager().is_init(), -+ "Only allowed during kernel init phase" -+ ); -+ -+ // Target all SPIs to the boot core only. -+ let mask = self.local_gic_target_mask(); -+ -+ self.shared_registers.lock(|regs| { -+ for i in regs.implemented_itargets_slice().iter() { -+ i.write( -+ ITARGETSR::Offset3.val(mask) -+ + ITARGETSR::Offset2.val(mask) -+ + ITARGETSR::Offset1.val(mask) -+ + ITARGETSR::Offset0.val(mask), -+ ); -+ } -+ -+ regs.CTLR.write(CTLR::Enable::SET); -+ }); -+ } -+ -+ /// Enable an interrupt. -+ pub fn enable(&self, irq_num: super::IRQNumber) { -+ let irq_num = irq_num.get(); -+ -+ // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 -+ // (division by 32) and arrive at the index for the respective ISENABLER[i]. -+ let enable_reg_index = irq_num >> 5; -+ let enable_bit: u32 = 1u32 << (irq_num modulo 32); -+ -+ // Check if we are handling a private or shared IRQ. -+ match irq_num { -+ // Private. -+ 0..=31 => { -+ let enable_reg = &self.banked_registers.ISENABLER; -+ enable_reg.set(enable_reg.get() | enable_bit); -+ } -+ // Shared. -+ _ => { -+ let enable_reg_index_shared = enable_reg_index - 1; -+ -+ self.shared_registers.lock(|regs| { -+ let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; -+ enable_reg.set(enable_reg.get() | enable_bit); -+ }); -+ } -+ } -+ } -+} - -diff -uNr 13_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs ---- 13_integrated_testing/src/bsp/device_driver/arm/gicv2.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs -@@ -0,0 +1,219 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! GICv2 Driver - ARM Generic Interrupt Controller v2. -+//! -+//! The following is a collection of excerpts with useful information from -+//! - `Programmer's Guide for ARMv8-A` -+//! - `ARM Generic Interrupt Controller Architecture Specification` -+//! -+//! # Programmer's Guide - 10.6.1 Configuration -+//! -+//! The GIC is accessed as a memory-mapped peripheral. -+//! -+//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core -+//! uses the same address to access its own private CPU interface. -+//! -+//! It is not possible for a core to access the CPU interface of another core. -+//! -+//! # Architecture Specification - 10.6.2 Initialization -+//! -+//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized -+//! after reset before it can deliver interrupts to the core. -+//! -+//! In the Distributor, software must configure the priority, target, security and enable individual -+//! interrupts. The Distributor must subsequently be enabled through its control register -+//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption -+//! settings. -+//! -+//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This -+//! prepares the GIC to deliver interrupts to the core. -+//! -+//! Before interrupts are expected in the core, software prepares the core to take interrupts by -+//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in -+//! PSTATE, and setting the routing controls. -+//! -+//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. -+//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. -+//! Individual interrupts can also be disabled (or enabled) in the distributor. -+//! -+//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must -+//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the -+//! core's priority mask. -+//! -+//! # Architecture Specification - 1.4.2 Interrupt types -+//! -+//! - Peripheral interrupt -+//! - Private Peripheral Interrupt (PPI) -+//! - This is a peripheral interrupt that is specific to a single processor. -+//! - Shared Peripheral Interrupt (SPI) -+//! - This is a peripheral interrupt that the Distributor can route to any of a specified -+//! combination of processors. -+//! -+//! - Software-generated interrupt (SGI) -+//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The -+//! system uses SGIs for interprocessor communication. -+//! - An SGI has edge-triggered properties. The software triggering of the interrupt is -+//! equivalent to the edge transition of the interrupt request signal. -+//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt -+//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, -+//! identifies the processor that requested the interrupt. -+//! -+//! # Architecture Specification - 2.2.1 Interrupt IDs -+//! -+//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 -+//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by -+//! the Distributor. -+//! -+//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: -+//! - Interrupt numbers 32..1019 are used for SPIs. -+//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These -+//! interrupts are banked in the Distributor. -+//! - A banked interrupt is one where the Distributor can have multiple interrupts with the -+//! same ID. A banked interrupt is identified uniquely by its ID number and its associated -+//! CPU interface number. Of the banked interrupt IDs: -+//! - 00..15 SGIs -+//! - 16..31 PPIs -+ -+mod gicc; -+mod gicd; -+ -+use crate::{bsp, cpu, driver, exception, synchronization, synchronization::InitStateLock}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+type HandlerTable = [Option; GICv2::NUM_IRQS]; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -+pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; -+ -+/// Representation of the GIC. -+pub struct GICv2 { -+ /// The Distributor. -+ gicd: gicd::GICD, -+ -+ /// The CPU Interface. -+ gicc: gicc::GICC, -+ -+ /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. -+ handler_table: InitStateLock, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl GICv2 { -+ const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. -+ const NUM_IRQS: usize = Self::MAX_IRQ_NUMBER + 1; -+ -+ /// Create an instance. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { -+ Self { -+ gicd: gicd::GICD::new(gicd_mmio_start_addr), -+ gicc: gicc::GICC::new(gicc_mmio_start_addr), -+ handler_table: InitStateLock::new([None; Self::NUM_IRQS]), -+ } -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+use synchronization::interface::ReadWriteEx; -+ -+impl driver::interface::DeviceDriver for GICv2 { -+ fn compatible(&self) -> &'static str { -+ "GICv2 (ARM Generic Interrupt Controller v2)" -+ } -+ -+ unsafe fn init(&self) -> Result<(), &'static str> { -+ if cpu::smp::core_id::() == bsp::cpu::BOOT_CORE_ID { -+ self.gicd.boot_core_init(); -+ } -+ -+ self.gicc.priority_accept_all(); -+ self.gicc.enable(); -+ -+ Ok(()) -+ } -+} -+ -+impl exception::asynchronous::interface::IRQManager for GICv2 { -+ type IRQNumberType = IRQNumber; -+ -+ fn register_handler( -+ &self, -+ irq_number: Self::IRQNumberType, -+ descriptor: exception::asynchronous::IRQDescriptor, -+ ) -> Result<(), &'static str> { -+ self.handler_table.write(|table| { -+ let irq_number = irq_number.get(); -+ -+ if table[irq_number].is_some() { -+ return Err("IRQ handler already registered"); -+ } -+ -+ table[irq_number] = Some(descriptor); -+ -+ Ok(()) -+ }) -+ } -+ -+ fn enable(&self, irq_number: Self::IRQNumberType) { -+ self.gicd.enable(irq_number); -+ } -+ -+ fn handle_pending_irqs<'irq_context>( -+ &'irq_context self, -+ ic: &exception::asynchronous::IRQContext<'irq_context>, -+ ) { -+ // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register -+ // (IAR). -+ let irq_number = self.gicc.pending_irq_number(ic); -+ -+ // Guard against spurious interrupts. -+ if irq_number > GICv2::MAX_IRQ_NUMBER { -+ return; -+ } -+ -+ // Call the IRQ handler. Panic if there is none. -+ self.handler_table.read(|table| { -+ match table[irq_number] { -+ None => panic!("No handler registered for IRQ {}", irq_number), -+ Some(descriptor) => { -+ // Call the IRQ handler. Panics on failure. -+ descriptor.handler.handle().expect("Error handling IRQ"); -+ } -+ } -+ }); -+ -+ // Signal completion of handling. -+ self.gicc.mark_comleted(irq_number as u32, ic); -+ } -+ -+ fn print_handler(&self) { -+ use crate::info; -+ -+ info!(" Peripheral handler:"); -+ -+ self.handler_table.read(|table| { -+ for (i, opt) in table.iter().skip(32).enumerate() { -+ if let Some(handler) = opt { -+ info!(" {: >3}. {}", i + 32, handler.name); -+ } -+ } -+ }); -+ } -+} - -diff -uNr 13_integrated_testing/src/bsp/device_driver/arm.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs ---- 13_integrated_testing/src/bsp/device_driver/arm.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs -@@ -0,0 +1,9 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! ARM driver top level. -+ -+pub mod gicv2; -+ -+pub use gicv2::*; - -diff -uNr 13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ---- 13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -@@ -6,7 +6,7 @@ - - use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, -- synchronization::NullLock, -+ synchronization::IRQSafeNullLock, - }; - use register::{mmio::*, register_bitfields, register_structs}; - -@@ -117,7 +117,7 @@ - - /// Representation of the GPIO HW. - pub struct GPIO { -- inner: NullLock, -+ inner: IRQSafeNullLock, - } - - //-------------------------------------------------------------------------------------------------- -@@ -193,7 +193,7 @@ - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { -- inner: NullLock::new(GPIOInner::new(mmio_start_addr)), -+ inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - -diff -uNr 13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ---- 13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs -@@ -0,0 +1,163 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Peripheral Interrupt regsler Driver. -+ -+use super::{InterruptController, PendingIRQs, PeripheralIRQ}; -+use crate::{ -+ bsp::device_driver::common::MMIODerefWrapper, -+ exception, synchronization, -+ synchronization::{IRQSafeNullLock, InitStateLock}, -+}; -+use register::{mmio::*, register_structs}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+register_structs! { -+ #[allow(non_snake_case)] -+ WORegisterBlock { -+ (0x00 => _reserved1), -+ (0x10 => ENABLE_1: WriteOnly), -+ (0x14 => ENABLE_2: WriteOnly), -+ (0x24 => @END), -+ } -+} -+ -+register_structs! { -+ #[allow(non_snake_case)] -+ RORegisterBlock { -+ (0x00 => _reserved1), -+ (0x04 => PENDING_1: ReadOnly), -+ (0x08 => PENDING_2: ReadOnly), -+ (0x0c => @END), -+ } -+} -+ -+/// Abstraction for the WriteOnly parts of the associated MMIO registers. -+type WriteOnlyRegisters = MMIODerefWrapper; -+ -+/// Abstraction for the ReadOnly parts of the associated MMIO registers. -+type ReadOnlyRegisters = MMIODerefWrapper; -+ -+type HandlerTable = -+ [Option; InterruptController::NUM_PERIPHERAL_IRQS]; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Representation of the peripheral interrupt controller. -+pub struct PeripheralIC { -+ /// Access to write registers is guarded with a lock. -+ wo_registers: IRQSafeNullLock, -+ -+ /// Register read access is unguarded. -+ ro_registers: ReadOnlyRegisters, -+ -+ /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. -+ handler_table: InitStateLock, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl PeripheralIC { -+ /// Create an instance. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ Self { -+ wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), -+ ro_registers: ReadOnlyRegisters::new(mmio_start_addr), -+ handler_table: InitStateLock::new([None; InterruptController::NUM_PERIPHERAL_IRQS]), -+ } -+ } -+ -+ /// Query the list of pending IRQs. -+ fn pending_irqs(&self) -> PendingIRQs { -+ let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) -+ | u64::from(self.ro_registers.PENDING_1.get()); -+ -+ PendingIRQs::new(pending_mask) -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+use synchronization::interface::{Mutex, ReadWriteEx}; -+ -+impl exception::asynchronous::interface::IRQManager for PeripheralIC { -+ type IRQNumberType = PeripheralIRQ; -+ -+ fn register_handler( -+ &self, -+ irq: Self::IRQNumberType, -+ descriptor: exception::asynchronous::IRQDescriptor, -+ ) -> Result<(), &'static str> { -+ self.handler_table.write(|table| { -+ let irq_number = irq.get(); -+ -+ if table[irq_number].is_some() { -+ return Err("IRQ handler already registered"); -+ } -+ -+ table[irq_number] = Some(descriptor); -+ -+ Ok(()) -+ }) -+ } -+ -+ fn enable(&self, irq: Self::IRQNumberType) { -+ self.wo_registers.lock(|regs| { -+ let enable_reg = if irq.get() <= 31 { -+ ®s.ENABLE_1 -+ } else { -+ ®s.ENABLE_2 -+ }; -+ -+ let enable_bit: u32 = 1 << (irq.get() modulo 32); -+ -+ // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable -+ // bits are unaffected. So we don't need read and OR'ing here. -+ enable_reg.set(enable_bit); -+ }); -+ } -+ -+ fn handle_pending_irqs<'irq_context>( -+ &'irq_context self, -+ _ic: &exception::asynchronous::IRQContext<'irq_context>, -+ ) { -+ self.handler_table.read(|table| { -+ for irq_number in self.pending_irqs() { -+ match table[irq_number] { -+ None => panic!("No handler registered for IRQ {}", irq_number), -+ Some(descriptor) => { -+ // Call the IRQ handler. Panics on failure. -+ descriptor.handler.handle().expect("Error handling IRQ"); -+ } -+ } -+ } -+ }) -+ } -+ -+ fn print_handler(&self) { -+ use crate::info; -+ -+ info!(" Peripheral handler:"); -+ -+ self.handler_table.read(|table| { -+ for (i, opt) in table.iter().enumerate() { -+ if let Some(handler) = opt { -+ info!(" {: >3}. {}", i, handler.name); -+ } -+ } -+ }); -+ } -+} - -diff -uNr 13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ---- 13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs -@@ -0,0 +1,131 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Interrupt Controller Driver. -+ -+mod peripheral_ic; -+ -+use crate::{driver, exception}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Wrapper struct for a bitmask indicating pending IRQ numbers. -+struct PendingIRQs { -+ bitmask: u64, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+pub type LocalIRQ = -+ exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -+pub type PeripheralIRQ = -+ exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; -+ -+/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -+#[derive(Copy, Clone)] -+pub enum IRQNumber { -+ Local(LocalIRQ), -+ Peripheral(PeripheralIRQ), -+} -+ -+/// Representation of the Interrupt Controller. -+pub struct InterruptController { -+ periph: peripheral_ic::PeripheralIC, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl PendingIRQs { -+ pub fn new(bitmask: u64) -> Self { -+ Self { bitmask } -+ } -+} -+ -+impl Iterator for PendingIRQs { -+ type Item = usize; -+ -+ fn next(&mut self) -> Option { -+ use core::intrinsics::cttz; -+ -+ let next = cttz(self.bitmask); -+ if next == 64 { -+ return None; -+ } -+ -+ self.bitmask &= !(1 << next); -+ -+ Some(next as usize) -+ } -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl InterruptController { -+ const MAX_LOCAL_IRQ_NUMBER: usize = 11; -+ const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; -+ const NUM_PERIPHERAL_IRQS: usize = Self::MAX_PERIPHERAL_IRQ_NUMBER + 1; -+ -+ /// Create an instance. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub const unsafe fn new(_local_mmio_start_addr: usize, periph_mmio_start_addr: usize) -> Self { -+ Self { -+ periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), -+ } -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// OS Interface Code -+//------------------------------------------------------------------------------ -+ -+impl driver::interface::DeviceDriver for InterruptController { -+ fn compatible(&self) -> &'static str { -+ "BCM Interrupt Controller" -+ } -+} -+ -+impl exception::asynchronous::interface::IRQManager for InterruptController { -+ type IRQNumberType = IRQNumber; -+ -+ fn register_handler( -+ &self, -+ irq: Self::IRQNumberType, -+ descriptor: exception::asynchronous::IRQDescriptor, -+ ) -> Result<(), &'static str> { -+ match irq { -+ IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), -+ IRQNumber::Peripheral(pirq) => self.periph.register_handler(pirq, descriptor), -+ } -+ } -+ -+ fn enable(&self, irq: Self::IRQNumberType) { -+ match irq { -+ IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), -+ IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), -+ } -+ } -+ -+ fn handle_pending_irqs<'irq_context>( -+ &'irq_context self, -+ ic: &exception::asynchronous::IRQContext<'irq_context>, -+ ) { -+ // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. -+ self.periph.handle_pending_irqs(ic) -+ } -+ -+ fn print_handler(&self) { -+ self.periph.print_handler(); -+ } -+} - -diff -uNr 13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ---- 13_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -@@ -5,8 +5,8 @@ - //! PL011 UART driver. - - use crate::{ -- bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, -- synchronization::NullLock, -+ bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, -+ synchronization, synchronization::IRQSafeNullLock, - }; - use core::fmt; - use register::{mmio::*, register_bitfields, register_structs}; -@@ -109,6 +109,48 @@ - ] - ], - -+ /// Interrupt FIFO Level Select Register -+ IFLS [ -+ /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as -+ /// follows. -+ RXIFLSEL OFFSET(3) NUMBITS(5) [ -+ OneEigth = 0b000, -+ OneQuarter = 0b001, -+ OneHalf = 0b010, -+ ThreeQuarters = 0b011, -+ SevenEights = 0b100 -+ ] -+ ], -+ -+ /// Interrupt Mask Set Clear Register -+ IMSC [ -+ /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR -+ /// interrupt. On a write of 1, the mask of the interrupt is set. A write of 0 clears the -+ /// mask. -+ RTIM OFFSET(6) NUMBITS(1) [ -+ Disabled = 0, -+ Enabled = 1 -+ ], -+ -+ /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. On -+ /// a write of 1, the mask of the interrupt is set. A write of 0 clears the mask. -+ RXIM OFFSET(4) NUMBITS(1) [ -+ Disabled = 0, -+ Enabled = 1 -+ ] -+ ], -+ -+ /// Masked Interrupt Status Register -+ MIS [ -+ /// Receive timeout masked interrupt status. Returns the masked interrupt state of the -+ /// UARTRTINTR interrupt. -+ RTMIS OFFSET(6) NUMBITS(1) [], -+ -+ /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR -+ /// interrupt. -+ RXMIS OFFSET(4) NUMBITS(1) [] -+ ], -+ - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts -@@ -127,7 +169,10 @@ - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), -- (0x34 => _reserved3), -+ (0x34 => IFLS: ReadWrite), -+ (0x38 => IMSC: ReadWrite), -+ (0x3C => _reserved3), -+ (0x40 => MIS: ReadOnly), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -@@ -136,6 +181,12 @@ - /// Abstraction for the associated MMIO registers. - type Registers = MMIODerefWrapper; - -+#[derive(PartialEq)] -+enum BlockingMode { -+ Blocking, -+ NonBlocking, -+} -+ - //-------------------------------------------------------------------------------------------------- - // Public Definitions - //-------------------------------------------------------------------------------------------------- -@@ -151,7 +202,8 @@ - - /// Representation of the UART. - pub struct PL011Uart { -- inner: NullLock, -+ inner: IRQSafeNullLock, -+ irq_number: bsp::device_driver::IRQNumber, - } - - //-------------------------------------------------------------------------------------------------- -@@ -190,6 +242,10 @@ - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on -+ self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); // RX FIFO fill level at 1/8 -+ self.registers -+ .IMSC -+ .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); // RX IRQ + RX timeout IRQ - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); -@@ -207,6 +263,35 @@ - - self.chars_written += 1; - } -+ -+ /// Retrieve a character. -+ fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { -+ // If RX FIFO is empty, -+ if self.registers.FR.matches_all(FR::RXFE::SET) { -+ // immediately return in non-blocking mode. -+ if blocking_mode == BlockingMode::NonBlocking { -+ return None; -+ } -+ -+ // Otherwise, wait until a char was received. -+ while self.registers.FR.matches_all(FR::RXFE::SET) { -+ cpu::nop(); -+ } -+ } -+ -+ // Read one character. -+ let mut ret = self.registers.DR.get() as u8 as char; -+ -+ // Convert carrige return to newline. -+ if ret == '\r' { -+ ret = '\n' -+ } -+ -+ // Update statistics. -+ self.chars_read += 1; -+ -+ Some(ret) -+ } - } - - /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -@@ -229,12 +314,18 @@ - } - - impl PL011Uart { -+ /// Create an instance. -+ /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. -- pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ pub const unsafe fn new( -+ mmio_start_addr: usize, -+ irq_number: bsp::device_driver::IRQNumber, -+ ) -> Self { - Self { -- inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), -+ inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), -+ irq_number, - } - } - } -@@ -254,6 +345,21 @@ - - Ok(()) - } -+ -+ fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { -+ use bsp::exception::asynchronous::irq_manager; -+ use exception::asynchronous::{interface::IRQManager, IRQDescriptor}; -+ -+ let descriptor = IRQDescriptor { -+ name: "BCM PL011 UART", -+ handler: self, -+ }; -+ -+ irq_manager().register_handler(self.irq_number, descriptor)?; -+ irq_manager().enable(self.irq_number); -+ -+ Ok(()) -+ } - } - - impl console::interface::Write for PL011Uart { -@@ -281,25 +387,8 @@ - - impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { -- self.inner.lock(|inner| { -- // Spin while RX FIFO empty is set. -- while inner.registers.FR.matches_all(FR::RXFE::SET) { -- cpu::nop(); -- } -- -- // Read one character. -- let mut ret = inner.registers.DR.get() as u8 as char; -- -- // Convert carrige return to newline. -- if ret == '\r' { -- ret = '\n' -- } -- -- // Update statistics. -- inner.chars_read += 1; -- -- ret -- }) -+ self.inner -+ .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) - } - - fn clear(&self) { -@@ -321,3 +410,24 @@ - self.inner.lock(|inner| inner.chars_read) - } - } -+ -+impl exception::asynchronous::interface::IRQHandler for PL011Uart { -+ fn handle(&self) -> Result<(), &'static str> { -+ self.inner.lock(|inner| { -+ let pending = inner.registers.MIS.extract(); -+ -+ // Clear all pending IRQs. -+ inner.registers.ICR.write(ICR::ALL::CLEAR); -+ -+ // Check for any kind of RX interrupt. -+ if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { -+ // Echo any received characters. -+ while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { -+ inner.write_char(c) -+ } -+ } -+ }); -+ -+ Ok(()) -+ } -+} - -diff -uNr 13_integrated_testing/src/bsp/device_driver/bcm.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs ---- 13_integrated_testing/src/bsp/device_driver/bcm.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs -@@ -5,7 +5,11 @@ - //! BCM driver top level. - - mod bcm2xxx_gpio; -+#[cfg(feature = "bsp_rpi3")] -+mod bcm2xxx_interrupt_controller; - mod bcm2xxx_pl011_uart; - - pub use bcm2xxx_gpio::*; -+#[cfg(feature = "bsp_rpi3")] -+pub use bcm2xxx_interrupt_controller::*; - pub use bcm2xxx_pl011_uart::*; - -diff -uNr 13_integrated_testing/src/bsp/device_driver.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs ---- 13_integrated_testing/src/bsp/device_driver.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs -@@ -4,9 +4,13 @@ - - //! Device driver. - -+#[cfg(feature = "bsp_rpi4")] -+mod arm; - #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] - mod bcm; - mod common; - -+#[cfg(feature = "bsp_rpi4")] -+pub use arm::*; - #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] - pub use bcm::*; - -diff -uNr 13_integrated_testing/src/bsp/raspberrypi/driver.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs ---- 13_integrated_testing/src/bsp/raspberrypi/driver.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs -@@ -12,7 +12,7 @@ - - /// Device Driver Manager type. - struct BSPDriverManager { -- device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -+ device_drivers: [&'static (dyn DeviceDriver + Sync); 3], - } - - //-------------------------------------------------------------------------------------------------- -@@ -20,7 +20,11 @@ - //-------------------------------------------------------------------------------------------------- - - static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { -- device_drivers: [&super::GPIO, &super::PL011_UART], -+ device_drivers: [ -+ &super::GPIO, -+ &super::PL011_UART, -+ &super::INTERRUPT_CONTROLLER, -+ ], - }; - - //-------------------------------------------------------------------------------------------------- - -diff -uNr 13_integrated_testing/src/bsp/raspberrypi/exception/asynchronous.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs ---- 13_integrated_testing/src/bsp/raspberrypi/exception/asynchronous.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs -@@ -0,0 +1,36 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! BSP asynchronous exception handling. -+ -+use crate::{bsp, exception}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+#[cfg(feature = "bsp_rpi3")] -+pub(in crate::bsp) mod irq_map { -+ use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; -+ -+ pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); -+} -+ -+#[cfg(feature = "bsp_rpi4")] -+pub(in crate::bsp) mod irq_map { -+ use super::bsp::device_driver::IRQNumber; -+ -+ pub const PL011_UART: IRQNumber = IRQNumber::new(153); -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return a reference to the IRQ manager. -+pub fn irq_manager() -> &'static impl exception::asynchronous::interface::IRQManager< -+ IRQNumberType = bsp::device_driver::IRQNumber, -+> { -+ &super::super::INTERRUPT_CONTROLLER -+} - -diff -uNr 13_integrated_testing/src/bsp/raspberrypi/exception.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs ---- 13_integrated_testing/src/bsp/raspberrypi/exception.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs -@@ -0,0 +1,7 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! BSP synchronous and asynchronous exception handling. -+ -+pub mod asynchronous; - -diff -uNr 13_integrated_testing/src/bsp/raspberrypi/memory.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs ---- 13_integrated_testing/src/bsp/raspberrypi/memory.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs -@@ -39,10 +39,12 @@ - pub mod mmio { - use super::*; - -- pub const START: usize = 0x3F00_0000; -- pub const GPIO_START: usize = START + GPIO_OFFSET; -- pub const PL011_UART_START: usize = START + UART_OFFSET; -- pub const END_INCLUSIVE: usize = 0x4000_FFFF; -+ pub const START: usize = 0x3F00_0000; -+ pub const PERIPHERAL_INTERRUPT_CONTROLLER_START: usize = START + 0x0000_B200; -+ pub const GPIO_START: usize = START + GPIO_OFFSET; -+ pub const PL011_UART_START: usize = START + UART_OFFSET; -+ pub const LOCAL_INTERRUPT_CONTROLLER_START: usize = 0x4000_0000; -+ pub const END_INCLUSIVE: usize = 0x4000_FFFF; - } - - /// Physical devices. -@@ -53,6 +55,8 @@ - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; -+ pub const GICD_START: usize = 0xFF84_1000; -+ pub const GICC_START: usize = 0xFF84_2000; - pub const END_INCLUSIVE: usize = 0xFF84_FFFF; - } - } - -diff -uNr 13_integrated_testing/src/bsp/raspberrypi.rs 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs ---- 13_integrated_testing/src/bsp/raspberrypi.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs -@@ -7,6 +7,7 @@ - pub mod console; - pub mod cpu; - pub mod driver; -+pub mod exception; - pub mod memory; - - //-------------------------------------------------------------------------------------------------- -@@ -17,8 +18,25 @@ - static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - --static PL011_UART: device_driver::PL011Uart = -- unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; -+static PL011_UART: device_driver::PL011Uart = unsafe { -+ device_driver::PL011Uart::new( -+ memory::map::mmio::PL011_UART_START, -+ exception::asynchronous::irq_map::PL011_UART, -+ ) -+}; -+ -+#[cfg(feature = "bsp_rpi3")] -+static INTERRUPT_CONTROLLER: device_driver::InterruptController = unsafe { -+ device_driver::InterruptController::new( -+ memory::map::mmio::LOCAL_INTERRUPT_CONTROLLER_START, -+ memory::map::mmio::PERIPHERAL_INTERRUPT_CONTROLLER_START, -+ ) -+}; -+ -+#[cfg(feature = "bsp_rpi4")] -+static INTERRUPT_CONTROLLER: device_driver::GICv2 = unsafe { -+ device_driver::GICv2::new(memory::map::mmio::GICD_START, memory::map::mmio::GICC_START) -+}; - - //-------------------------------------------------------------------------------------------------- - // Public Code - -diff -uNr 13_integrated_testing/src/driver.rs 14_exceptions_part2_peripheral_IRQs/src/driver.rs ---- 13_integrated_testing/src/driver.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/driver.rs -@@ -23,6 +23,14 @@ - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } -+ -+ /// Called by the kernel to register and enable the device's IRQ handlers, if any. -+ /// -+ /// Rust's type system will prevent a call to this function unless the calling instance -+ /// itself has static lifetime. -+ fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { -+ Ok(()) -+ } - } - - /// Device driver management functions. - -diff -uNr 13_integrated_testing/src/exception/asynchronous.rs 14_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs ---- 13_integrated_testing/src/exception/asynchronous.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs -@@ -8,3 +8,138 @@ - #[path = "../_arch/aarch64/exception/asynchronous.rs"] - mod arch_exception_async; - pub use arch_exception_async::*; -+ -+use core::{fmt, marker::PhantomData}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Interrupt descriptor. -+#[derive(Copy, Clone)] -+pub struct IRQDescriptor { -+ /// Descriptive name. -+ pub name: &'static str, -+ -+ /// Reference to handler trait object. -+ pub handler: &'static (dyn interface::IRQHandler + Sync), -+} -+ -+/// IRQContext token. -+/// -+/// An instance of this type indicates that the local core is currently executing in IRQ -+/// context, aka executing an interrupt vector or subcalls of it. -+/// -+/// Concept and implementation derived from the `CriticalSection` introduced in -+/// https://github.com/rust-embedded/bare-metal -+#[derive(Clone, Copy)] -+pub struct IRQContext<'irq_context> { -+ _0: PhantomData<&'irq_context ()>, -+} -+ -+/// Asynchronous exception handling interfaces. -+pub mod interface { -+ -+ /// Implemented by types that handle IRQs. -+ pub trait IRQHandler { -+ /// Called when the corresponding interrupt is asserted. -+ fn handle(&self) -> Result<(), &'static str>; -+ } -+ -+ /// IRQ management functions. -+ /// -+ /// The `BSP` is supposed to supply one global instance. Typically implemented by the -+ /// platform's interrupt controller. -+ pub trait IRQManager { -+ /// The IRQ number type depends on the implementation. -+ type IRQNumberType; -+ -+ /// Register a handler. -+ fn register_handler( -+ &self, -+ irq_number: Self::IRQNumberType, -+ descriptor: super::IRQDescriptor, -+ ) -> Result<(), &'static str>; -+ -+ /// Enable an interrupt in the controller. -+ fn enable(&self, irq_number: Self::IRQNumberType); -+ -+ /// Handle pending interrupts. -+ /// -+ /// This function is called directly from the CPU's IRQ exception vector. On AArch64, -+ /// this means that the respective CPU core has disabled exception handling. -+ /// This function can therefore not be preempted and runs start to finish. -+ /// -+ /// Takes an IRQContext token to ensure it can only be called from IRQ context. -+ #[allow(clippy::trivially_copy_pass_by_ref)] -+ fn handle_pending_irqs<'irq_context>( -+ &'irq_context self, -+ ic: &super::IRQContext<'irq_context>, -+ ); -+ -+ /// Print list of registered handlers. -+ fn print_handler(&self); -+ } -+} -+ -+/// A wrapper type for IRQ numbers with integrated range sanity check. -+#[derive(Copy, Clone)] -+pub struct IRQNumber(usize); -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl<'irq_context> IRQContext<'irq_context> { -+ /// Creates an IRQContext token. -+ /// -+ /// # Safety -+ /// -+ /// - This must only be called when the current core is in an interrupt context and will not -+ /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For -+ /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. -+ /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code -+ /// must not be able to influence the lifetime picked for this type, since that might cause it -+ /// to be inferred to `'static`. -+ #[inline(always)] -+ pub unsafe fn new() -> Self { -+ IRQContext { _0: PhantomData } -+ } -+} -+ -+impl IRQNumber<{ MAX_INCLUSIVE }> { -+ /// Creates a new instance if number <= MAX_INCLUSIVE. -+ pub const fn new(number: usize) -> Self { -+ assert!(number <= MAX_INCLUSIVE); -+ -+ Self { 0: number } -+ } -+ -+ /// Return the wrapped number. -+ pub fn get(self) -> usize { -+ self.0 -+ } -+} -+ -+impl fmt::Display for IRQNumber<{ MAX_INCLUSIVE }> { -+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -+ write!(f, "{}", self.0) -+ } -+} -+ -+/// Executes the provided closure while IRQs are masked on the executing core. -+/// -+/// While the function temporarily changes the HW state of the executing core, it restores it to the -+/// previous state before returning, so this is deemed safe. -+#[inline(always)] -+pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { -+ let ret: T; -+ -+ unsafe { -+ let saved = local_irq_mask_save(); -+ ret = f(); -+ local_irq_restore(saved); -+ } -+ -+ ret -+} - -diff -uNr 13_integrated_testing/src/lib.rs 14_exceptions_part2_peripheral_IRQs/src/lib.rs ---- 13_integrated_testing/src/lib.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/lib.rs -@@ -13,12 +13,17 @@ - //! - //! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. - //! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -+//! - [`bsp::exception::asynchronous::irq_manager()`] - Returns a reference to the kernel's [IRQ -+//! Handling interface]. - //! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. -+//! - [`state::state_manager()`] - Returns a reference to the kernel's [state management] instance. - //! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. - //! - //! [console interface]: ../libkernel/console/interface/index.html - //! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -+//! [IRQ Handling interface]: ../libkernel/exception/asynchronous/interface/trait.IRQManager.html - //! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html -+//! [state management]: ../libkernel/state/struct.StateManager.html - //! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html - //! - //! # Code organization and architecture -@@ -107,9 +112,11 @@ - //! - `crate::bsp::memory::*` - - #![allow(incomplete_features)] -+#![feature(asm)] - #![feature(const_fn_fn_ptr_basics)] - #![feature(const_generics)] - #![feature(const_panic)] -+#![feature(core_intrinsics)] - #![feature(format_args_nl)] - #![feature(global_asm)] - #![feature(linkage)] -@@ -137,6 +144,7 @@ - pub mod exception; - pub mod memory; - pub mod print; -+pub mod state; - pub mod time; - - //-------------------------------------------------------------------------------------------------- - -diff -uNr 13_integrated_testing/src/main.rs 14_exceptions_part2_peripheral_IRQs/src/main.rs ---- 13_integrated_testing/src/main.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/main.rs -@@ -11,7 +11,7 @@ - #![no_main] - #![no_std] - --use libkernel::{bsp, console, driver, exception, info, memory, time}; -+use libkernel::{bsp, cpu, driver, exception, info, memory, state, time, warn}; - - /// Early init code. - /// -@@ -21,8 +21,8 @@ - /// - The init calls in this function must appear in the correct order: - /// - Virtual memory must be activated before the device drivers. - /// - Without it, any atomic operations, e.g. the yet-to-be-introduced spinlocks in the device --/// drivers (which currently employ NullLocks instead of spinlocks), will fail to work on --/// the RPi SoCs. -+/// drivers (which currently employ IRQSafeNullLocks instead of spinlocks), will fail to -+/// work on the RPi SoCs. - #[no_mangle] - unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; -@@ -42,14 +42,27 @@ - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - -+ // Let device drivers register and enable their handlers with the interrupt controller. -+ for i in bsp::driver::driver_manager().all_device_drivers() { -+ if let Err(msg) = i.register_and_enable_irq_handler() { -+ warn!("Error registering IRQ handler: {}", msg); -+ } -+ } -+ -+ // Unmask interrupts on the boot CPU core. -+ exception::asynchronous::local_irq_unmask(); -+ -+ // Announce conclusion of the kernel_init() phase. -+ state::state_manager().transition_to_single_core_main(); -+ - // Transition from unsafe to safe. - kernel_main() - } - - /// The main function running after the early init. - fn kernel_main() -> ! { -- use console::interface::All; - use driver::interface::DriverManager; -+ use exception::asynchronous::interface::IRQManager; - - info!("Booting on: {}", bsp::board_name()); - -@@ -76,9 +89,9 @@ - info!(" {}. {}", i + 1, driver.compatible()); - } - -+ info!("Registered IRQ handlers:"); -+ bsp::exception::asynchronous::irq_manager().print_handler(); -+ - info!("Echoing input now"); -- loop { -- let c = bsp::console::console().read_char(); -- bsp::console::console().write_char(c); -- } -+ cpu::wait_forever(); - } - -diff -uNr 13_integrated_testing/src/panic_wait.rs 14_exceptions_part2_peripheral_IRQs/src/panic_wait.rs ---- 13_integrated_testing/src/panic_wait.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/panic_wait.rs -@@ -4,7 +4,7 @@ - - //! A panic handler that infinitely waits. - --use crate::{bsp, cpu}; -+use crate::{bsp, cpu, exception}; - use core::{fmt, panic::PanicInfo}; - - //-------------------------------------------------------------------------------------------------- -@@ -46,6 +46,8 @@ - - #[panic_handler] - fn panic(info: &PanicInfo) -> ! { -+ unsafe { exception::asynchronous::local_irq_mask() }; -+ - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - -diff -uNr 13_integrated_testing/src/state.rs 14_exceptions_part2_peripheral_IRQs/src/state.rs ---- 13_integrated_testing/src/state.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/state.rs -@@ -0,0 +1,92 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! State information about the kernel itself. -+ -+use core::sync::atomic::{AtomicU8, Ordering}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Different stages in the kernel execution. -+#[derive(Copy, Clone, Eq, PartialEq)] -+enum State { -+ /// The kernel starts booting in this state. -+ Init, -+ -+ /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of -+ /// `kernel_init()`, after all init calls are done). -+ SingleCoreMain, -+ -+ /// The kernel transitions to this state when it boots the secondary cores, aka switches -+ /// exectution mode to symmetric multiprocessing (SMP). -+ MultiCoreMain, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Maintains the kernel state and state transitions. -+pub struct StateManager(AtomicU8); -+ -+//-------------------------------------------------------------------------------------------------- -+// Global instances -+//-------------------------------------------------------------------------------------------------- -+ -+static STATE_MANAGER: StateManager = StateManager::new(); -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return a reference to the global StateManager. -+pub fn state_manager() -> &'static StateManager { -+ &STATE_MANAGER -+} -+ -+impl StateManager { -+ const INIT: u8 = 0; -+ const SINGLE_CORE_MAIN: u8 = 1; -+ const MULTI_CORE_MAIN: u8 = 2; -+ -+ /// Create a new instance. -+ pub const fn new() -> Self { -+ Self(AtomicU8::new(Self::INIT)) -+ } -+ -+ /// Return the current state. -+ fn state(&self) -> State { -+ let state = self.0.load(Ordering::Acquire); -+ -+ match state { -+ Self::INIT => State::Init, -+ Self::SINGLE_CORE_MAIN => State::SingleCoreMain, -+ Self::MULTI_CORE_MAIN => State::MultiCoreMain, -+ _ => panic!("Invalid KERNEL_STATE"), -+ } -+ } -+ -+ /// Return if the kernel is still in an init state. -+ pub fn is_init(&self) -> bool { -+ self.state() == State::Init -+ } -+ -+ /// Transition from Init to SingleCoreMain. -+ pub fn transition_to_single_core_main(&self) { -+ if self -+ .0 -+ .compare_exchange( -+ Self::INIT, -+ Self::SINGLE_CORE_MAIN, -+ Ordering::Acquire, -+ Ordering::Relaxed, -+ ) -+ .is_err() -+ { -+ panic!("transition_to_single_core_main() called while state != Init"); -+ } -+ } -+} - -diff -uNr 13_integrated_testing/src/synchronization.rs 14_exceptions_part2_peripheral_IRQs/src/synchronization.rs ---- 13_integrated_testing/src/synchronization.rs -+++ 14_exceptions_part2_peripheral_IRQs/src/synchronization.rs -@@ -27,6 +27,21 @@ - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } -+ -+ /// A reader-writer exclusion type. -+ /// -+ /// The implementing object allows either a number of readers or at most one writer at any point -+ /// in time. -+ pub trait ReadWriteEx { -+ /// The type of encapsulated data. -+ type Data; -+ -+ /// Grants temporary mutable access to the encapsulated data. -+ fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; -+ -+ /// Grants temporary immutable access to the encapsulated data. -+ fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R; -+ } - } - - /// A pseudo-lock for teaching purposes. -@@ -35,8 +50,18 @@ - /// other cores to the contained data. This part is preserved for later lessons. - /// - /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is --/// executing single-threaded, aka only running on a single core with interrupts disabled. --pub struct NullLock -+/// executing on a single core. -+pub struct IRQSafeNullLock -+where -+ T: ?Sized, -+{ -+ data: UnsafeCell, -+} -+ -+/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. -+/// -+/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. -+pub struct InitStateLock - where - T: ?Sized, - { -@@ -47,10 +72,22 @@ - // Public Code - //-------------------------------------------------------------------------------------------------- - --unsafe impl Send for NullLock where T: ?Sized + Send {} --unsafe impl Sync for NullLock where T: ?Sized + Send {} -+unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} -+unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} -+ -+impl IRQSafeNullLock { -+ /// Create an instance. -+ pub const fn new(data: T) -> Self { -+ Self { -+ data: UnsafeCell::new(data), -+ } -+ } -+} -+ -+unsafe impl Send for InitStateLock where T: ?Sized + Send {} -+unsafe impl Sync for InitStateLock where T: ?Sized + Send {} - --impl NullLock { -+impl InitStateLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { -@@ -62,8 +99,9 @@ - //------------------------------------------------------------------------------ - // OS Interface Code - //------------------------------------------------------------------------------ -+use crate::{exception, state}; - --impl interface::Mutex for NullLock { -+impl interface::Mutex for IRQSafeNullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { -@@ -71,6 +109,32 @@ - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - -+ // Execute the closure while IRQs are masked. -+ exception::asynchronous::exec_with_irq_masked(|| f(data)) -+ } -+} -+ -+impl interface::ReadWriteEx for InitStateLock { -+ type Data = T; -+ -+ fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { -+ assert!( -+ state::state_manager().is_init(), -+ "InitStateLock::write called after kernel init phase" -+ ); -+ assert!( -+ !exception::asynchronous::is_local_irq_masked(), -+ "InitStateLock::write called with IRQs unmasked" -+ ); -+ -+ let data = unsafe { &mut *self.data.get() }; -+ -+ f(data) -+ } -+ -+ fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { -+ let data = unsafe { &*self.data.get() }; -+ - f(data) - } - } - -diff -uNr 13_integrated_testing/tests/03_exception_irq_sanity.rs 14_exceptions_part2_peripheral_IRQs/tests/03_exception_irq_sanity.rs ---- 13_integrated_testing/tests/03_exception_irq_sanity.rs -+++ 14_exceptions_part2_peripheral_IRQs/tests/03_exception_irq_sanity.rs -@@ -0,0 +1,68 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! IRQ handling sanity tests. -+ -+#![feature(custom_test_frameworks)] -+#![no_main] -+#![no_std] -+#![reexport_test_harness_main = "test_main"] -+#![test_runner(libkernel::test_runner)] -+ -+mod panic_exit_failure; -+ -+use libkernel::{bsp, cpu, exception}; -+use test_macros::kernel_test; -+ -+#[no_mangle] -+unsafe fn kernel_init() -> ! { -+ bsp::console::qemu_bring_up_console(); -+ -+ exception::handling_init(); -+ exception::asynchronous::local_irq_unmask(); -+ -+ test_main(); -+ -+ cpu::qemu_exit_success() -+} -+ -+/// Check that IRQ masking works. -+#[kernel_test] -+fn local_irq_mask_works() { -+ // Precondition: IRQs are unmasked. -+ assert!(exception::asynchronous::is_local_irq_masked()); -+ -+ unsafe { exception::asynchronous::local_irq_mask() }; -+ assert!(!exception::asynchronous::is_local_irq_masked()); -+ -+ // Restore earlier state. -+ unsafe { exception::asynchronous::local_irq_unmask() }; -+} -+ -+/// Check that IRQ unmasking works. -+#[kernel_test] -+fn local_irq_unmask_works() { -+ // Precondition: IRQs are masked. -+ unsafe { exception::asynchronous::local_irq_mask() }; -+ assert!(!exception::asynchronous::is_local_irq_masked()); -+ -+ unsafe { exception::asynchronous::local_irq_unmask() }; -+ assert!(exception::asynchronous::is_local_irq_masked()); -+} -+ -+/// Check that IRQ mask save is saving "something". -+#[kernel_test] -+fn local_irq_mask_save_works() { -+ // Precondition: IRQs are unmasked. -+ assert!(exception::asynchronous::is_local_irq_masked()); -+ -+ let first = unsafe { exception::asynchronous::local_irq_mask_save() }; -+ assert!(!exception::asynchronous::is_local_irq_masked()); -+ -+ let second = unsafe { exception::asynchronous::local_irq_mask_save() }; -+ assert_ne!(first, second); -+ -+ unsafe { exception::asynchronous::local_irq_restore(first) }; -+ assert!(exception::asynchronous::is_local_irq_masked()); -+} - -``` diff --git a/14_exceptions_part2_peripheral_IRQs/build.rs b/14_exceptions_part2_peripheral_IRQs/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/14_exceptions_part2_peripheral_IRQs/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu.rs b/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 7d146d230..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - // Expect the boot core to start in EL2. - if (bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id()) - && (CurrentEL.get() == CurrentEL::EL::EL2.value) - { - el2_to_el1_transition() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -/// Transition from EL2 to EL1. -/// -/// # Safety -/// -/// - The HW state of EL1 must be prepared in a sound way. -/// - Exception return from EL2 must must continue execution in EL1 with -/// `runtime_init::runtime_init()`. -#[inline(always)] -unsafe fn el2_to_el1_transition() -> ! { - use crate::runtime_init; - - // Enable timer counter registers for EL1. - CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); - - // No offset for reading the counters. - CNTVOFF_EL2.set(0); - - // Set EL1 execution state to AArch64. - HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); - - // Set up a simulated exception return. - // - // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a - // stack pointer. - SPSR_EL2.write( - SPSR_EL2::D::Masked - + SPSR_EL2::A::Masked - + SPSR_EL2::I::Masked - + SPSR_EL2::F::Masked - + SPSR_EL2::M::EL1h, - ); - - // Second, let the link register point to runtime_init(). - ELR_EL2.set(runtime_init::runtime_init as *const () as u64); - - // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. - SP_EL1.set(bsp::memory::boot_core_stack_end() as u64); - - // Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. - asm::eret() -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- -use qemu_exit::QEMUExit; - -const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); - -/// Make the host QEMU binary execute `exit(1)`. -pub fn qemu_exit_failure() -> ! { - QEMU_EXIT_HANDLE.exit_failure() -} - -/// Make the host QEMU binary execute `exit(0)`. -pub fn qemu_exit_success() -> ! { - QEMU_EXIT_HANDLE.exit_success() -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/smp.rs b/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.S b/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.S deleted file mode 100644 index ee3b5497e..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.S +++ /dev/null @@ -1,138 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -/// Call the function provided by parameter `\handler` after saving the exception context. Provide -/// the context as the first parameter to '\handler'. -.macro CALL_WITH_CONTEXT handler - // Make room on the stack for the exception context. - sub sp, sp, #16 * 17 - - // Store all general purpose registers on the stack. - stp x0, x1, [sp, #16 * 0] - stp x2, x3, [sp, #16 * 1] - stp x4, x5, [sp, #16 * 2] - stp x6, x7, [sp, #16 * 3] - stp x8, x9, [sp, #16 * 4] - stp x10, x11, [sp, #16 * 5] - stp x12, x13, [sp, #16 * 6] - stp x14, x15, [sp, #16 * 7] - stp x16, x17, [sp, #16 * 8] - stp x18, x19, [sp, #16 * 9] - stp x20, x21, [sp, #16 * 10] - stp x22, x23, [sp, #16 * 11] - stp x24, x25, [sp, #16 * 12] - stp x26, x27, [sp, #16 * 13] - stp x28, x29, [sp, #16 * 14] - - // Add the exception link register (ELR_EL1) and the saved program status (SPSR_EL1). - mrs x1, ELR_EL1 - mrs x2, SPSR_EL1 - - stp lr, x1, [sp, #16 * 15] - str x2, [sp, #16 * 16] - - // x0 is the first argument for the function called through `\handler`. - mov x0, sp - - // Call `\handler`. - bl \handler - - // After returning from exception handling code, replay the saved context and return via `eret`. - b __exception_restore_context -.endm - -.macro FIQ_SUSPEND -1: wfe - b 1b -.endm - -//-------------------------------------------------------------------------------------------------- -// The exception vector table. -//-------------------------------------------------------------------------------------------------- -.section .exception_vectors, "ax", @progbits - -// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. -.align 11 - -// Export a symbol for the Rust code to use. -__exception_vector_start: - -// Current exception level with SP_EL0. -// -// .org sets the offset relative to section start. -// -// # Safety -// -// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. -.org 0x000 - CALL_WITH_CONTEXT current_el0_synchronous -.org 0x080 - CALL_WITH_CONTEXT current_el0_irq -.org 0x100 - FIQ_SUSPEND -.org 0x180 - CALL_WITH_CONTEXT current_el0_serror - -// Current exception level with SP_ELx, x > 0. -.org 0x200 - CALL_WITH_CONTEXT current_elx_synchronous -.org 0x280 - CALL_WITH_CONTEXT current_elx_irq -.org 0x300 - FIQ_SUSPEND -.org 0x380 - CALL_WITH_CONTEXT current_elx_serror - -// Lower exception level, AArch64 -.org 0x400 - CALL_WITH_CONTEXT lower_aarch64_synchronous -.org 0x480 - CALL_WITH_CONTEXT lower_aarch64_irq -.org 0x500 - FIQ_SUSPEND -.org 0x580 - CALL_WITH_CONTEXT lower_aarch64_serror - -// Lower exception level, AArch32 -.org 0x600 - CALL_WITH_CONTEXT lower_aarch32_synchronous -.org 0x680 - CALL_WITH_CONTEXT lower_aarch32_irq -.org 0x700 - FIQ_SUSPEND -.org 0x780 - CALL_WITH_CONTEXT lower_aarch32_serror -.org 0x800 - -//-------------------------------------------------------------------------------------------------- -// Helper functions -//-------------------------------------------------------------------------------------------------- -.section .text - -__exception_restore_context: - ldr w19, [sp, #16 * 16] - ldp lr, x20, [sp, #16 * 15] - - msr SPSR_EL1, x19 - msr ELR_EL1, x20 - - ldp x0, x1, [sp, #16 * 0] - ldp x2, x3, [sp, #16 * 1] - ldp x4, x5, [sp, #16 * 2] - ldp x6, x7, [sp, #16 * 3] - ldp x8, x9, [sp, #16 * 4] - ldp x10, x11, [sp, #16 * 5] - ldp x12, x13, [sp, #16 * 6] - ldp x14, x15, [sp, #16 * 7] - ldp x16, x17, [sp, #16 * 8] - ldp x18, x19, [sp, #16 * 9] - ldp x20, x21, [sp, #16 * 10] - ldp x22, x23, [sp, #16 * 11] - ldp x24, x25, [sp, #16 * 12] - ldp x26, x27, [sp, #16 * 13] - ldp x28, x29, [sp, #16 * 14] - - add sp, sp, #16 * 17 - - eret diff --git a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs b/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs deleted file mode 100644 index a4451cde6..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs +++ /dev/null @@ -1,260 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural synchronous and asynchronous exception handling. - -use crate::{bsp, exception}; -use core::{cell::UnsafeCell, fmt}; -use cortex_a::{barrier, regs::*}; -use register::InMemoryRegister; - -// Assembly counterpart to this file. -global_asm!(include_str!("exception.S")); - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Wrapper struct for memory copy of SPSR_EL1. -#[repr(transparent)] -struct SpsrEL1(InMemoryRegister); - -/// The exception context as it is stored on the stack on exception entry. -#[repr(C)] -struct ExceptionContext { - /// General Purpose Registers. - gpr: [u64; 30], - - /// The link register, aka x30. - lr: u64, - - /// Exception link register. The program counter at the time the exception happened. - elr_el1: u64, - - /// Saved program status. - spsr_el1: SpsrEL1, -} - -/// Wrapper struct for pretty printing ESR_EL1. -struct EsrEL1; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Prints verbose information about the exception and then panics. -fn default_exception_handler(e: &ExceptionContext) { - panic!( - "\n\nCPU Exception!\n\ - FAR_EL1: {:#018x}\n\ - {}\n\ - {}", - FAR_EL1.get(), - EsrEL1 {}, - e - ); -} - -//------------------------------------------------------------------------------ -// Current, EL0 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn current_el0_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_el0_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_el0_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Current, ELx -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { - use exception::asynchronous::interface::IRQManager; - - let token = &exception::asynchronous::IRQContext::new(); - bsp::exception::asynchronous::irq_manager().handle_pending_irqs(token); -} - -#[no_mangle] -unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Lower, AArch64 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Lower, AArch32 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Pretty printing -//------------------------------------------------------------------------------ - -/// Human readable ESR_EL1. -#[rustfmt::skip] -impl fmt::Display for EsrEL1 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let esr_el1 = ESR_EL1.extract(); - - // Raw print of whole register. - writeln!(f, "ESR_EL1: {:#010x}", esr_el1.get())?; - - // Raw print of exception class. - write!(f, " Exception Class (EC) : {:#x}", esr_el1.read(ESR_EL1::EC))?; - - // Exception class, translation. - let ec_translation = match esr_el1.read_as_enum(ESR_EL1::EC) { - Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", - _ => "N/A", - }; - writeln!(f, " - {}", ec_translation)?; - - // Raw print of instruction specific syndrome. - write!(f, " Instr Specific Syndrome (ISS): {:#x}", esr_el1.read(ESR_EL1::ISS))?; - - Ok(()) - } -} - -/// Human readable SPSR_EL1. -#[rustfmt::skip] -impl fmt::Display for SpsrEL1 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Raw value. - writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; - - let to_flag_str = |x| -> _ { - if x { "Set" } else { "Not set" } - }; - - writeln!(f, " Flags:")?; - writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; - writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; - writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; - writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - writeln!(f, " Exception handling state:")?; - writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; - writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; - writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; - writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; - - write!(f, " Illegal Execution State (IL): {}", - to_flag_str(self.0.is_set(SPSR_EL1::IL)) - )?; - - Ok(()) - } -} - -/// Human readable print of the exception context. -impl fmt::Display for ExceptionContext { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; - writeln!(f, "{}", self.spsr_el1)?; - writeln!(f)?; - writeln!(f, "General purpose register:")?; - - #[rustfmt::skip] - let alternating = |x| -> _ { - if x % 2 == 0 { " " } else { "\n" } - }; - - // Print two registers per line. - for (i, reg) in self.gpr.iter().enumerate() { - write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; - } - write!(f, " lr : {:#018x}", self.lr)?; - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use crate::exception::PrivilegeLevel; - -/// The processing element's current privilege level. -pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { - let el = CurrentEL.read_as_enum(CurrentEL::EL); - match el { - Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), - Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), - Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), - _ => (PrivilegeLevel::Unknown, "Unknown"), - } -} - -/// Init exception handling by setting the exception vector base address register. -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must -/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference -/// Manual. -pub unsafe fn handling_init() { - // Provided by exception.S. - extern "Rust" { - static __exception_vector_start: UnsafeCell<()>; - } - - VBAR_EL1.set(__exception_vector_start.get() as u64); - - // Force VBAR update to complete before next instruction. - barrier::isb(barrier::SY); -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs b/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs deleted file mode 100644 index df6a5c3f7..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs +++ /dev/null @@ -1,143 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural asynchronous exception handling. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -mod daif_bits { - pub const IRQ: u8 = 0b0010; -} - -trait DaifField { - fn daif_field() -> register::Field; -} - -struct Debug; -struct SError; -struct IRQ; -struct FIQ; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl DaifField for Debug { - fn daif_field() -> register::Field { - DAIF::D - } -} - -impl DaifField for SError { - fn daif_field() -> register::Field { - DAIF::A - } -} - -impl DaifField for IRQ { - fn daif_field() -> register::Field { - DAIF::I - } -} - -impl DaifField for FIQ { - fn daif_field() -> register::Field { - DAIF::F - } -} - -fn is_masked() -> bool -where - T: DaifField, -{ - DAIF.is_set(T::daif_field()) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Returns whether IRQs are masked on the executing core. -pub fn is_local_irq_masked() -> bool { - !is_masked::() -} - -/// Unmask IRQs on the executing core. -/// -/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. -/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: -/// -/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional -/// synchronization." -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -#[inline(always)] -pub unsafe fn local_irq_unmask() { - #[rustfmt::skip] - asm!( - "msr DAIFClr, {arg}", - arg = const daif_bits::IRQ, - options(nomem, nostack, preserves_flags) - ); -} - -/// Mask IRQs on the executing core. -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -#[inline(always)] -pub unsafe fn local_irq_mask() { - #[rustfmt::skip] - asm!( - "msr DAIFSet, {arg}", - arg = const daif_bits::IRQ, - options(nomem, nostack, preserves_flags) - ); -} - -/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -#[inline(always)] -pub unsafe fn local_irq_mask_save() -> u64 { - let saved = DAIF.get(); - local_irq_mask(); - - saved -} - -/// Restore the interrupt mask bits (DAIF) using the callee's argument. -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -/// - No sanity checks on the input. -#[inline(always)] -pub unsafe fn local_irq_restore(saved: u64) { - DAIF.set(saved); -} - -/// Print the AArch64 exceptions status. -#[rustfmt::skip] -pub fn print_state() { - use crate::info; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - info!(" Debug: {}", to_mask_str(is_masked::())); - info!(" SError: {}", to_mask_str(is_masked::())); - info!(" IRQ: {}", to_mask_str(is_masked::())); - info!(" FIQ: {}", to_mask_str(is_masked::())); -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs b/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs deleted file mode 100644 index 1ccb3fd71..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs +++ /dev/null @@ -1,370 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management Unit Driver. -//! -//! Static translation tables, compiled on boot; Everything 64 KiB granule. - -use super::{AccessPermissions, AttributeFields, MemAttributes}; -use crate::{bsp, memory}; -use core::convert; -use cortex_a::{barrier, regs::*}; -use register::{register_bitfields, InMemoryRegister}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. -register_bitfields! {u64, - STAGE1_TABLE_DESCRIPTOR [ - /// Physical address of the next descriptor. - NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. -register_bitfields! {u64, - STAGE1_PAGE_DESCRIPTOR [ - /// Privileged execute-never. - PXN OFFSET(53) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). - OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - /// Access flag. - AF OFFSET(10) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Shareability field. - SH OFFSET(8) NUMBITS(2) [ - OuterShareable = 0b10, - InnerShareable = 0b11 - ], - - /// Access Permissions. - AP OFFSET(6) NUMBITS(2) [ - RW_EL1 = 0b00, - RW_EL1_EL0 = 0b01, - RO_EL1 = 0b10, - RO_EL1_EL0 = 0b11 - ], - - /// Memory attributes index into the MAIR_EL1 register. - AttrIndx OFFSET(2) NUMBITS(3) [], - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -const SIXTYFOUR_KIB_SHIFT: usize = 16; // log2(64 * 1024) -const FIVETWELVE_MIB_SHIFT: usize = 29; // log2(512 * 1024 * 1024) - -/// A table descriptor for 64 KiB aperture. -/// -/// The output points to the next table. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct TableDescriptor(u64); - -/// A page descriptor with 64 KiB aperture. -/// -/// The output points to physical memory. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct PageDescriptor(u64); - -/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB -/// aligned, hence the "reverse" order of appearance. -#[repr(C)] -#[repr(align(65536))] -struct FixedSizeTranslationTable { - /// Page descriptors, covering 64 KiB windows per entry. - lvl3: [[PageDescriptor; 8192]; NUM_TABLES], - - /// Table descriptors, covering 512 MiB windows. - lvl2: [TableDescriptor; NUM_TABLES], -} - -/// Usually evaluates to 1 GiB for RPi3 and 4 GiB for RPi 4. -const NUM_LVL2_TABLES: usize = bsp::memory::mmu::addr_space_size() >> FIVETWELVE_MIB_SHIFT; -type ArchTranslationTable = FixedSizeTranslationTable; - -trait BaseAddr { - fn base_addr_u64(&self) -> u64; - fn base_addr_usize(&self) -> usize; -} - -/// Constants for indexing the MAIR_EL1. -#[allow(dead_code)] -mod mair { - pub const DEVICE: u64 = 0; - pub const NORMAL: u64 = 1; -} - -/// Memory Management Unit type. -struct MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -/// The translation tables. -/// -/// # Safety -/// -/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". -static mut KERNEL_TABLES: ArchTranslationTable = ArchTranslationTable::new(); - -static MMU: MemoryManagementUnit = MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl BaseAddr for [T; N] { - fn base_addr_u64(&self) -> u64 { - self as *const T as u64 - } - - fn base_addr_usize(&self) -> usize { - self as *const _ as usize - } -} - -impl convert::From for TableDescriptor { - fn from(next_lvl_table_addr: usize) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = next_lvl_table_addr >> SIXTYFOUR_KIB_SHIFT; - val.write( - STAGE1_TABLE_DESCRIPTOR::VALID::True - + STAGE1_TABLE_DESCRIPTOR::TYPE::Table - + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64), - ); - - TableDescriptor(val.get()) - } -} - -/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. -impl convert::From - for register::FieldValue -{ - fn from(attribute_fields: AttributeFields) -> Self { - // Memory attributes. - let mut desc = match attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => { - STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::NORMAL) - } - MemAttributes::Device => { - STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::DEVICE) - } - }; - - // Access Permissions. - desc += match attribute_fields.acc_perms { - AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, - AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, - }; - - // Execute Never. - desc += if attribute_fields.execute_never { - STAGE1_PAGE_DESCRIPTOR::PXN::True - } else { - STAGE1_PAGE_DESCRIPTOR::PXN::False - }; - - desc - } -} - -impl PageDescriptor { - /// Create an instance. - fn new(output_addr: usize, attribute_fields: AttributeFields) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = output_addr as u64 >> SIXTYFOUR_KIB_SHIFT; - val.write( - STAGE1_PAGE_DESCRIPTOR::VALID::True - + STAGE1_PAGE_DESCRIPTOR::AF::True - + attribute_fields.into() - + STAGE1_PAGE_DESCRIPTOR::TYPE::Table - + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted), - ); - - Self(val.get()) - } -} - -impl FixedSizeTranslationTable<{ NUM_TABLES }> { - /// Create an instance. - pub const fn new() -> Self { - assert!(NUM_TABLES > 0); - - Self { - lvl3: [[PageDescriptor(0); 8192]; NUM_TABLES], - lvl2: [TableDescriptor(0); NUM_TABLES], - } - } -} - -/// Setup function for the MAIR_EL1 register. -fn set_up_mair() { - // Define the memory types being mapped. - MAIR_EL1.write( - // Attribute 1 - Cacheable normal DRAM. - MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + - MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + - - // Attribute 0 - Device. - MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, - ); -} - -/// Iterates over all static translation table entries and fills them at once. -/// -/// # Safety -/// -/// - Modifies a `static mut`. Ensure it only happens from here. -unsafe fn populate_tt_entries() -> Result<(), &'static str> { - for (l2_nr, l2_entry) in KERNEL_TABLES.lvl2.iter_mut().enumerate() { - *l2_entry = KERNEL_TABLES.lvl3[l2_nr].base_addr_usize().into(); - - for (l3_nr, l3_entry) in KERNEL_TABLES.lvl3[l2_nr].iter_mut().enumerate() { - let virt_addr = (l2_nr << FIVETWELVE_MIB_SHIFT) + (l3_nr << SIXTYFOUR_KIB_SHIFT); - - let (output_addr, attribute_fields) = - bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; - - *l3_entry = PageDescriptor::new(output_addr, attribute_fields); - } - } - - Ok(()) -} - -/// Configure various settings of stage 1 of the EL1 translation regime. -fn configure_translation_control() { - let ips = ID_AA64MMFR0_EL1.read(ID_AA64MMFR0_EL1::PARange); - - TCR_EL1.write( - TCR_EL1::TBI0::Ignored - + TCR_EL1::IPS.val(ips) - + TCR_EL1::TG0::KiB_64 - + TCR_EL1::SH0::Inner - + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::EPD0::EnableTTBR0Walks - + TCR_EL1::T0SZ.val(32), // TTBR0 spans 4 GiB total. - ); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the MMU instance. -pub fn mmu() -> &'static impl memory::mmu::interface::MMU { - &MMU -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl memory::mmu::interface::MMU for MemoryManagementUnit { - unsafe fn init(&self) -> Result<(), &'static str> { - // Fail early if translation granule is not supported. Both RPis support it, though. - if !ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported) { - return Err("Translation granule not supported in HW"); - } - - // Prepare the memory attribute indirection register. - set_up_mair(); - - // Populate translation tables. - populate_tt_entries()?; - - // Set the "Translation Table Base Register". - TTBR0_EL1.set_baddr(KERNEL_TABLES.lvl2.base_addr_u64()); - - configure_translation_control(); - - // Switch the MMU on. - // - // First, force all previous changes to be seen before the MMU is enabled. - barrier::isb(barrier::SY); - - // Enable the MMU and turn on data and instruction caching. - SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); - - // Force MMU init to complete before next instruction. - barrier::isb(barrier::SY); - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check if the size of `struct TableDescriptor` is as expected. - #[kernel_test] - fn size_of_tabledescriptor_equals_64_bit() { - assert_eq!( - core::mem::size_of::(), - core::mem::size_of::() - ); - } - - /// Check if the size of `struct PageDescriptor` is as expected. - #[kernel_test] - fn size_of_pagedescriptor_equals_64_bit() { - assert_eq!( - core::mem::size_of::(), - core::mem::size_of::() - ); - } - - /// Check if KERNEL_TABLES is in .bss. - #[kernel_test] - fn kernel_tables_in_bss() { - let bss_range = bsp::memory::bss_range_inclusive(); - let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; - - assert!(bss_range.contains(&kernel_tables_addr)); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/time.rs b/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/time.rs deleted file mode 100644 index af98ddd01..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) - } - - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; - - Duration::from_nanos(current_count / frq) - } - - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } - - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get() as u64; - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; - } - - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); - - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); - - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} - - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs deleted file mode 100644 index 3fe1fa555..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(feature = "bsp_rpi4")] -mod arm; -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(feature = "bsp_rpi4")] -pub use arm::*; -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs deleted file mode 100644 index 6d9d3bdf0..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! ARM driver top level. - -pub mod gicv2; - -pub use gicv2::*; diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs deleted file mode 100644 index 9981b9794..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs +++ /dev/null @@ -1,219 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! GICv2 Driver - ARM Generic Interrupt Controller v2. -//! -//! The following is a collection of excerpts with useful information from -//! - `Programmer's Guide for ARMv8-A` -//! - `ARM Generic Interrupt Controller Architecture Specification` -//! -//! # Programmer's Guide - 10.6.1 Configuration -//! -//! The GIC is accessed as a memory-mapped peripheral. -//! -//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core -//! uses the same address to access its own private CPU interface. -//! -//! It is not possible for a core to access the CPU interface of another core. -//! -//! # Architecture Specification - 10.6.2 Initialization -//! -//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized -//! after reset before it can deliver interrupts to the core. -//! -//! In the Distributor, software must configure the priority, target, security and enable individual -//! interrupts. The Distributor must subsequently be enabled through its control register -//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption -//! settings. -//! -//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This -//! prepares the GIC to deliver interrupts to the core. -//! -//! Before interrupts are expected in the core, software prepares the core to take interrupts by -//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in -//! PSTATE, and setting the routing controls. -//! -//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. -//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. -//! Individual interrupts can also be disabled (or enabled) in the distributor. -//! -//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must -//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the -//! core's priority mask. -//! -//! # Architecture Specification - 1.4.2 Interrupt types -//! -//! - Peripheral interrupt -//! - Private Peripheral Interrupt (PPI) -//! - This is a peripheral interrupt that is specific to a single processor. -//! - Shared Peripheral Interrupt (SPI) -//! - This is a peripheral interrupt that the Distributor can route to any of a specified -//! combination of processors. -//! -//! - Software-generated interrupt (SGI) -//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The -//! system uses SGIs for interprocessor communication. -//! - An SGI has edge-triggered properties. The software triggering of the interrupt is -//! equivalent to the edge transition of the interrupt request signal. -//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt -//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, -//! identifies the processor that requested the interrupt. -//! -//! # Architecture Specification - 2.2.1 Interrupt IDs -//! -//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 -//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by -//! the Distributor. -//! -//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: -//! - Interrupt numbers 32..1019 are used for SPIs. -//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These -//! interrupts are banked in the Distributor. -//! - A banked interrupt is one where the Distributor can have multiple interrupts with the -//! same ID. A banked interrupt is identified uniquely by its ID number and its associated -//! CPU interface number. Of the banked interrupt IDs: -//! - 00..15 SGIs -//! - 16..31 PPIs - -mod gicc; -mod gicd; - -use crate::{bsp, cpu, driver, exception, synchronization, synchronization::InitStateLock}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -type HandlerTable = [Option; GICv2::NUM_IRQS]; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; - -/// Representation of the GIC. -pub struct GICv2 { - /// The Distributor. - gicd: gicd::GICD, - - /// The CPU Interface. - gicc: gicc::GICC, - - /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. - handler_table: InitStateLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GICv2 { - const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. - const NUM_IRQS: usize = Self::MAX_IRQ_NUMBER + 1; - - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { - Self { - gicd: gicd::GICD::new(gicd_mmio_start_addr), - gicc: gicc::GICC::new(gicc_mmio_start_addr), - handler_table: InitStateLock::new([None; Self::NUM_IRQS]), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::ReadWriteEx; - -impl driver::interface::DeviceDriver for GICv2 { - fn compatible(&self) -> &'static str { - "GICv2 (ARM Generic Interrupt Controller v2)" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - if cpu::smp::core_id::() == bsp::cpu::BOOT_CORE_ID { - self.gicd.boot_core_init(); - } - - self.gicc.priority_accept_all(); - self.gicc.enable(); - - Ok(()) - } -} - -impl exception::asynchronous::interface::IRQManager for GICv2 { - type IRQNumberType = IRQNumber; - - fn register_handler( - &self, - irq_number: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, - ) -> Result<(), &'static str> { - self.handler_table.write(|table| { - let irq_number = irq_number.get(); - - if table[irq_number].is_some() { - return Err("IRQ handler already registered"); - } - - table[irq_number] = Some(descriptor); - - Ok(()) - }) - } - - fn enable(&self, irq_number: Self::IRQNumberType) { - self.gicd.enable(irq_number); - } - - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { - // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register - // (IAR). - let irq_number = self.gicc.pending_irq_number(ic); - - // Guard against spurious interrupts. - if irq_number > GICv2::MAX_IRQ_NUMBER { - return; - } - - // Call the IRQ handler. Panic if there is none. - self.handler_table.read(|table| { - match table[irq_number] { - None => panic!("No handler registered for IRQ {}", irq_number), - Some(descriptor) => { - // Call the IRQ handler. Panics on failure. - descriptor.handler.handle().expect("Error handling IRQ"); - } - } - }); - - // Signal completion of handling. - self.gicc.mark_comleted(irq_number as u32, ic); - } - - fn print_handler(&self) { - use crate::info; - - info!(" Peripheral handler:"); - - self.handler_table.read(|table| { - for (i, opt) in table.iter().skip(32).enumerate() { - if let Some(handler) = opt { - info!(" {: >3}. {}", i + 32, handler.name); - } - } - }); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs deleted file mode 100644 index c6708cdcd..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs +++ /dev/null @@ -1,137 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! GICC Driver - GIC CPU interface. - -use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -register_bitfields! { - u32, - - /// CPU Interface Control Register - CTLR [ - Enable OFFSET(0) NUMBITS(1) [] - ], - - /// Interrupt Priority Mask Register - PMR [ - Priority OFFSET(0) NUMBITS(8) [] - ], - - /// Interrupt Acknowledge Register - IAR [ - InterruptID OFFSET(0) NUMBITS(10) [] - ], - - /// End of Interrupt Register - EOIR [ - EOIINTID OFFSET(0) NUMBITS(10) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x000 => CTLR: ReadWrite), - (0x004 => PMR: ReadWrite), - (0x008 => _reserved1), - (0x00C => IAR: ReadWrite), - (0x010 => EOIR: ReadWrite), - (0x014 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Representation of the GIC CPU interface. -pub struct GICC { - registers: Registers, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GICC { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Accept interrupts of any priority. - /// - /// Quoting the GICv2 Architecture Specification: - /// - /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field - /// value." - /// - /// # Safety - /// - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - pub fn priority_accept_all(&self) { - self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. - } - - /// Enable the interface - start accepting IRQs. - /// - /// # Safety - /// - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - pub fn enable(&self) { - self.registers.CTLR.write(CTLR::Enable::SET); - } - - /// Extract the number of the highest-priority pending IRQ. - /// - /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. - /// - /// # Safety - /// - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - #[allow(clippy::trivially_copy_pass_by_ref)] - pub fn pending_irq_number<'irq_context>( - &self, - _ic: &exception::asynchronous::IRQContext<'irq_context>, - ) -> usize { - self.registers.IAR.read(IAR::InterruptID) as usize - } - - /// Complete handling of the currently active IRQ. - /// - /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. - /// - /// To be called after `pending_irq_number()`. - /// - /// # Safety - /// - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - #[allow(clippy::trivially_copy_pass_by_ref)] - pub fn mark_comleted<'irq_context>( - &self, - irq_number: u32, - _ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { - self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs deleted file mode 100644 index 35f7eecd0..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs +++ /dev/null @@ -1,195 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! GICD Driver - GIC Distributor. -//! -//! # Glossary -//! - SPI - Shared Peripheral Interrupt. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, state, synchronization, - synchronization::IRQSafeNullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -register_bitfields! { - u32, - - /// Distributor Control Register - CTLR [ - Enable OFFSET(0) NUMBITS(1) [] - ], - - /// Interrupt Controller Type Register - TYPER [ - ITLinesNumber OFFSET(0) NUMBITS(5) [] - ], - - /// Interrupt Processor Targets Registers - ITARGETSR [ - Offset3 OFFSET(24) NUMBITS(8) [], - Offset2 OFFSET(16) NUMBITS(8) [], - Offset1 OFFSET(8) NUMBITS(8) [], - Offset0 OFFSET(0) NUMBITS(8) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - SharedRegisterBlock { - (0x000 => CTLR: ReadWrite), - (0x004 => TYPER: ReadOnly), - (0x008 => _reserved1), - (0x104 => ISENABLER: [ReadWrite; 31]), - (0x108 => _reserved2), - (0x820 => ITARGETSR: [ReadWrite; 248]), - (0x824 => @END), - } -} - -register_structs! { - #[allow(non_snake_case)] - BankedRegisterBlock { - (0x000 => _reserved1), - (0x100 => ISENABLER: ReadWrite), - (0x104 => _reserved2), - (0x800 => ITARGETSR: [ReadOnly; 8]), - (0x804 => @END), - } -} - -/// Abstraction for the non-banked parts of the associated MMIO registers. -type SharedRegisters = MMIODerefWrapper; - -/// Abstraction for the banked parts of the associated MMIO registers. -type BankedRegisters = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Representation of the GIC Distributor. -pub struct GICD { - /// Access to shared registers is guarded with a lock. - shared_registers: IRQSafeNullLock, - - /// Access to banked registers is unguarded. - banked_registers: BankedRegisters, -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl SharedRegisters { - /// Return the number of IRQs that this HW implements. - #[inline(always)] - fn num_irqs(&mut self) -> usize { - // Query number of implemented IRQs. - // - // Refer to GICv2 Architecture Specification, Section 4.3.2. - ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 - } - - /// Return a slice of the implemented ITARGETSR. - #[inline(always)] - fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { - assert!(self.num_irqs() >= 36); - - // Calculate the max index of the shared ITARGETSR array. - // - // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS - // register has four entries, so shift right by two. Subtract one because we start - // counting at zero. - let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; - - // Rust automatically inserts slice range sanity check, i.e. max >= min. - &self.ITARGETSR[0..spi_itargetsr_max_index] - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use synchronization::interface::Mutex; - -impl GICD { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), - banked_registers: BankedRegisters::new(mmio_start_addr), - } - } - - /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. - /// - /// Quoting the GICv2 Architecture Specification: - /// - /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that - /// corresponds only to the processor reading the register." - fn local_gic_target_mask(&self) -> u32 { - self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) - } - - /// Route all SPIs to the boot core and enable the distributor. - pub fn boot_core_init(&self) { - assert!( - state::state_manager().is_init(), - "Only allowed during kernel init phase" - ); - - // Target all SPIs to the boot core only. - let mask = self.local_gic_target_mask(); - - self.shared_registers.lock(|regs| { - for i in regs.implemented_itargets_slice().iter() { - i.write( - ITARGETSR::Offset3.val(mask) - + ITARGETSR::Offset2.val(mask) - + ITARGETSR::Offset1.val(mask) - + ITARGETSR::Offset0.val(mask), - ); - } - - regs.CTLR.write(CTLR::Enable::SET); - }); - } - - /// Enable an interrupt. - pub fn enable(&self, irq_num: super::IRQNumber) { - let irq_num = irq_num.get(); - - // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 - // (division by 32) and arrive at the index for the respective ISENABLER[i]. - let enable_reg_index = irq_num >> 5; - let enable_bit: u32 = 1u32 << (irq_num % 32); - - // Check if we are handling a private or shared IRQ. - match irq_num { - // Private. - 0..=31 => { - let enable_reg = &self.banked_registers.ISENABLER; - enable_reg.set(enable_reg.get() | enable_bit); - } - // Shared. - _ => { - let enable_reg_index_shared = enable_reg_index - 1; - - self.shared_registers.lock(|regs| { - let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; - enable_reg.set(enable_reg.get() | enable_bit); - }); - } - } - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 5e4c9e705..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -#[cfg(feature = "bsp_rpi3")] -mod bcm2xxx_interrupt_controller; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -#[cfg(feature = "bsp_rpi3")] -pub use bcm2xxx_interrupt_controller::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index 88e68be13..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::IRQSafeNullLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - inner: IRQSafeNullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; - use core::time::Duration; - - // The Linux 2837 GPIO driver waits 1 µs between the steps. - const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs deleted file mode 100644 index 6b11224b6..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +++ /dev/null @@ -1,131 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Interrupt Controller Driver. - -mod peripheral_ic; - -use crate::{driver, exception}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Wrapper struct for a bitmask indicating pending IRQ numbers. -struct PendingIRQs { - bitmask: u64, -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub type LocalIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -pub type PeripheralIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; - -/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -#[derive(Copy, Clone)] -pub enum IRQNumber { - Local(LocalIRQ), - Peripheral(PeripheralIRQ), -} - -/// Representation of the Interrupt Controller. -pub struct InterruptController { - periph: peripheral_ic::PeripheralIC, -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl PendingIRQs { - pub fn new(bitmask: u64) -> Self { - Self { bitmask } - } -} - -impl Iterator for PendingIRQs { - type Item = usize; - - fn next(&mut self) -> Option { - use core::intrinsics::cttz; - - let next = cttz(self.bitmask); - if next == 64 { - return None; - } - - self.bitmask &= !(1 << next); - - Some(next as usize) - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl InterruptController { - const MAX_LOCAL_IRQ_NUMBER: usize = 11; - const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; - const NUM_PERIPHERAL_IRQS: usize = Self::MAX_PERIPHERAL_IRQ_NUMBER + 1; - - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(_local_mmio_start_addr: usize, periph_mmio_start_addr: usize) -> Self { - Self { - periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl driver::interface::DeviceDriver for InterruptController { - fn compatible(&self) -> &'static str { - "BCM Interrupt Controller" - } -} - -impl exception::asynchronous::interface::IRQManager for InterruptController { - type IRQNumberType = IRQNumber; - - fn register_handler( - &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, - ) -> Result<(), &'static str> { - match irq { - IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), - IRQNumber::Peripheral(pirq) => self.periph.register_handler(pirq, descriptor), - } - } - - fn enable(&self, irq: Self::IRQNumberType) { - match irq { - IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), - IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), - } - } - - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { - // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. - self.periph.handle_pending_irqs(ic) - } - - fn print_handler(&self) { - self.periph.print_handler(); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs deleted file mode 100644 index 94af8d746..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +++ /dev/null @@ -1,163 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Peripheral Interrupt regsler Driver. - -use super::{InterruptController, PendingIRQs, PeripheralIRQ}; -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, - exception, synchronization, - synchronization::{IRQSafeNullLock, InitStateLock}, -}; -use register::{mmio::*, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -register_structs! { - #[allow(non_snake_case)] - WORegisterBlock { - (0x00 => _reserved1), - (0x10 => ENABLE_1: WriteOnly), - (0x14 => ENABLE_2: WriteOnly), - (0x24 => @END), - } -} - -register_structs! { - #[allow(non_snake_case)] - RORegisterBlock { - (0x00 => _reserved1), - (0x04 => PENDING_1: ReadOnly), - (0x08 => PENDING_2: ReadOnly), - (0x0c => @END), - } -} - -/// Abstraction for the WriteOnly parts of the associated MMIO registers. -type WriteOnlyRegisters = MMIODerefWrapper; - -/// Abstraction for the ReadOnly parts of the associated MMIO registers. -type ReadOnlyRegisters = MMIODerefWrapper; - -type HandlerTable = - [Option; InterruptController::NUM_PERIPHERAL_IRQS]; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Representation of the peripheral interrupt controller. -pub struct PeripheralIC { - /// Access to write registers is guarded with a lock. - wo_registers: IRQSafeNullLock, - - /// Register read access is unguarded. - ro_registers: ReadOnlyRegisters, - - /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. - handler_table: InitStateLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PeripheralIC { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), - ro_registers: ReadOnlyRegisters::new(mmio_start_addr), - handler_table: InitStateLock::new([None; InterruptController::NUM_PERIPHERAL_IRQS]), - } - } - - /// Query the list of pending IRQs. - fn pending_irqs(&self) -> PendingIRQs { - let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) - | u64::from(self.ro_registers.PENDING_1.get()); - - PendingIRQs::new(pending_mask) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::{Mutex, ReadWriteEx}; - -impl exception::asynchronous::interface::IRQManager for PeripheralIC { - type IRQNumberType = PeripheralIRQ; - - fn register_handler( - &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, - ) -> Result<(), &'static str> { - self.handler_table.write(|table| { - let irq_number = irq.get(); - - if table[irq_number].is_some() { - return Err("IRQ handler already registered"); - } - - table[irq_number] = Some(descriptor); - - Ok(()) - }) - } - - fn enable(&self, irq: Self::IRQNumberType) { - self.wo_registers.lock(|regs| { - let enable_reg = if irq.get() <= 31 { - ®s.ENABLE_1 - } else { - ®s.ENABLE_2 - }; - - let enable_bit: u32 = 1 << (irq.get() % 32); - - // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable - // bits are unaffected. So we don't need read and OR'ing here. - enable_reg.set(enable_bit); - }); - } - - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - _ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { - self.handler_table.read(|table| { - for irq_number in self.pending_irqs() { - match table[irq_number] { - None => panic!("No handler registered for IRQ {}", irq_number), - Some(descriptor) => { - // Call the IRQ handler. Panics on failure. - descriptor.handler.handle().expect("Error handling IRQ"); - } - } - } - }) - } - - fn print_handler(&self) { - use crate::info; - - info!(" Peripheral handler:"); - - self.handler_table.read(|table| { - for (i, opt) in table.iter().enumerate() { - if let Some(handler) = opt { - info!(" {: >3}. {}", i, handler.name); - } - } - }); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index 3207539c0..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,433 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, - synchronization, synchronization::IRQSafeNullLock, -}; -use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt FIFO Level Select Register - IFLS [ - /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as - /// follows. - RXIFLSEL OFFSET(3) NUMBITS(5) [ - OneEigth = 0b000, - OneQuarter = 0b001, - OneHalf = 0b010, - ThreeQuarters = 0b011, - SevenEights = 0b100 - ] - ], - - /// Interrupt Mask Set Clear Register - IMSC [ - /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR - /// interrupt. On a write of 1, the mask of the interrupt is set. A write of 0 clears the - /// mask. - RTIM OFFSET(6) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. On - /// a write of 1, the mask of the interrupt is set. A write of 0 clears the mask. - RXIM OFFSET(4) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ] - ], - - /// Masked Interrupt Status Register - MIS [ - /// Receive timeout masked interrupt status. Returns the masked interrupt state of the - /// UARTRTINTR interrupt. - RTMIS OFFSET(6) NUMBITS(1) [], - - /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR - /// interrupt. - RXMIS OFFSET(4) NUMBITS(1) [] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => IFLS: ReadWrite), - (0x38 => IMSC: ReadWrite), - (0x3C => _reserved3), - (0x40 => MIS: ReadOnly), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -#[derive(PartialEq)] -enum BlockingMode { - Blocking, - NonBlocking, -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - inner: IRQSafeNullLock, - irq_number: bsp::device_driver::IRQNumber, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - pub fn init(&mut self) { - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); // RX FIFO fill level at 1/8 - self.registers - .IMSC - .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); // RX IRQ + RX timeout IRQ - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } - - /// Retrieve a character. - fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { - // If RX FIFO is empty, - if self.registers.FR.matches_all(FR::RXFE::SET) { - // immediately return in non-blocking mode. - if blocking_mode == BlockingMode::NonBlocking { - return None; - } - - // Otherwise, wait until a char was received. - while self.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - } - - // Read one character. - let mut ret = self.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - self.chars_read += 1; - - Some(ret) - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new( - mmio_start_addr: usize, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { - Self { - inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), - irq_number, - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - - Ok(()) - } - - fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { - use bsp::exception::asynchronous::irq_manager; - use exception::asynchronous::{interface::IRQManager, IRQDescriptor}; - - let descriptor = IRQDescriptor { - name: "BCM PL011 UART", - handler: self, - }; - - irq_manager().register_handler(self.irq_number, descriptor)?; - irq_manager().enable(self.irq_number); - - Ok(()) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner - .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} - -impl exception::asynchronous::interface::IRQHandler for PL011Uart { - fn handle(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| { - let pending = inner.registers.MIS.extract(); - - // Clear all pending IRQs. - inner.registers.ICR.write(ICR::ALL::CLEAR); - - // Check for any kind of RX interrupt. - if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { - // Echo any received characters. - while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { - inner.write_char(c) - } - } - }); - - Ok(()) - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/common.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs deleted file mode 100644 index 25af58d6d..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod exception; -pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = unsafe { - device_driver::PL011Uart::new( - memory::map::mmio::PL011_UART_START, - exception::asynchronous::irq_map::PL011_UART, - ) -}; - -#[cfg(feature = "bsp_rpi3")] -static INTERRUPT_CONTROLLER: device_driver::InterruptController = unsafe { - device_driver::InterruptController::new( - memory::map::mmio::LOCAL_INTERRUPT_CONTROLLER_START, - memory::map::mmio::PERIPHERAL_INTERRUPT_CONTROLLER_START, - ) -}; - -#[cfg(feature = "bsp_rpi4")] -static INTERRUPT_CONTROLLER: device_driver::GICv2 = unsafe { - device_driver::GICv2::new(memory::map::mmio::GICD_START, memory::map::mmio::GICC_START) -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs deleted file mode 100644 index 16b2f59bc..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps -/// than on real hardware due to QEMU's abstractions. -/// -/// For the RPi, nothing needs to be done. -pub fn qemu_bring_up_console() {} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/cpu.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index 0b2348fbc..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 3], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [ - &super::GPIO, - &super::PL011_UART, - &super::INTERRUPT_CONTROLLER, - ], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs deleted file mode 100644 index 55e821198..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! BSP synchronous and asynchronous exception handling. - -pub mod asynchronous; diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs deleted file mode 100644 index 787d59269..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! BSP asynchronous exception handling. - -use crate::{bsp, exception}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -#[cfg(feature = "bsp_rpi3")] -pub(in crate::bsp) mod irq_map { - use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; - - pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); -} - -#[cfg(feature = "bsp_rpi4")] -pub(in crate::bsp) mod irq_map { - use super::bsp::device_driver::IRQNumber; - - pub const PL011_UART: IRQNumber = IRQNumber::new(153); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the IRQ manager. -pub fn irq_manager() -> &'static impl exception::asynchronous::interface::IRQManager< - IRQNumberType = bsp::device_driver::IRQNumber, -> { - &super::super::INTERRUPT_CONTROLLER -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 90d096ffe..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,47 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - __ro_start = .; - .text : - { - *(.text._start) *(.text*) - } - - .exception_vectors : - { - *(.exception_vectors*) - } - - .rodata : - { - *(.rodata*) - } - . = ALIGN(65536); /* Fill up to 64 KiB */ - __ro_end = .; - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 8cb07905b..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,112 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. - -pub mod mmu; - -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; - static __ro_start: UnsafeCell<()>; - static __ro_end: UnsafeCell<()>; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's memory map. -#[rustfmt::skip] -pub(super) mod map { - pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; - - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const START: usize = 0x3F00_0000; - pub const PERIPHERAL_INTERRUPT_CONTROLLER_START: usize = START + 0x0000_B200; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const LOCAL_INTERRUPT_CONTROLLER_START: usize = 0x4000_0000; - pub const END_INCLUSIVE: usize = 0x4000_FFFF; - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const GICD_START: usize = 0xFF84_1000; - pub const GICC_START: usize = 0xFF84_2000; - pub const END_INCLUSIVE: usize = 0xFF84_FFFF; - } -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Start address of the Read-Only (RO) range. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_start() -> usize { - unsafe { __ro_start.get() as usize } -} - -/// Size of the Read-Only (RO) range of the kernel binary. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_end() -> usize { - unsafe { __ro_end.get() as usize } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs b/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs deleted file mode 100644 index d5078b5a0..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs +++ /dev/null @@ -1,116 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management Unit. - -use super::map as memory_map; -use crate::memory::mmu::*; -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -const NUM_MEM_RANGES: usize = 2; - -/// The virtual memory layout. -/// -/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. -/// It is agnostic of the paging granularity that the architecture's MMU will use. -pub static LAYOUT: KernelVirtualLayout<{ NUM_MEM_RANGES }> = KernelVirtualLayout::new( - memory_map::END_INCLUSIVE, - [ - TranslationDescriptor { - name: "Kernel code and RO data", - virtual_range: ro_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadOnly, - execute_never: false, - }, - }, - TranslationDescriptor { - name: "Device MMIO", - virtual_range: mmio_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - }, - ], -); - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn ro_range_inclusive() -> RangeInclusive { - // Notice the subtraction to turn the exclusive end into an inclusive end. - #[allow(clippy::range_minus_one)] - RangeInclusive::new(super::ro_start(), super::ro_end() - 1) -} - -fn mmio_range_inclusive() -> RangeInclusive { - RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the address space size in bytes. -pub const fn addr_space_size() -> usize { - memory_map::END_INCLUSIVE + 1 -} - -/// Return a reference to the virtual memory layout. -pub fn virt_mem_layout() -> &'static KernelVirtualLayout<{ NUM_MEM_RANGES }> { - &LAYOUT -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check alignment of the kernel's virtual memory layout sections. - #[kernel_test] - fn virt_mem_layout_sections_are_64KiB_aligned() { - const SIXTYFOUR_KIB: usize = 65536; - - for i in LAYOUT.inner().iter() { - let start: usize = *(i.virtual_range)().start(); - let end: usize = *(i.virtual_range)().end() + 1; - - assert_eq!(start % SIXTYFOUR_KIB, 0); - assert_eq!(end % SIXTYFOUR_KIB, 0); - assert!(end >= start); - } - } - - /// Ensure the kernel's virtual memory layout is free of overlaps. - #[kernel_test] - fn virt_mem_layout_has_no_overlaps() { - let layout = virt_mem_layout().inner(); - - for (i, first) in layout.iter().enumerate() { - for second in layout.iter().skip(i + 1) { - let first_range = first.virtual_range; - let second_range = second.virtual_range; - - assert!(!first_range().contains(second_range().start())); - assert!(!first_range().contains(second_range().end())); - assert!(!second_range().contains(first_range().start())); - assert!(!second_range().contains(first_range().end())); - } - } - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/console.rs b/14_exceptions_part2_peripheral_IRQs/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/cpu.rs b/14_exceptions_part2_peripheral_IRQs/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/14_exceptions_part2_peripheral_IRQs/src/cpu/smp.rs b/14_exceptions_part2_peripheral_IRQs/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/14_exceptions_part2_peripheral_IRQs/src/driver.rs b/14_exceptions_part2_peripheral_IRQs/src/driver.rs deleted file mode 100644 index b7d44dad5..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/driver.rs +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - - /// Called by the kernel to register and enable the device's IRQ handlers, if any. - /// - /// Rust's type system will prevent a call to this function unless the calling instance - /// itself has static lifetime. - fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { - Ok(()) - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/exception.rs b/14_exceptions_part2_peripheral_IRQs/src/exception.rs deleted file mode 100644 index 81ea2b26e..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/exception.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronous and asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/exception.rs"] -mod arch_exception; -pub use arch_exception::*; - -pub mod asynchronous; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Kernel privilege levels. -#[allow(missing_docs)] -#[derive(PartialEq)] -pub enum PrivilegeLevel { - User, - Kernel, - Hypervisor, - Unknown, -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Libkernel unit tests must execute in kernel mode. - #[kernel_test] - fn test_runner_executes_in_kernel_mode() { - let (level, _) = current_privilege_level(); - - assert!(level == PrivilegeLevel::Kernel) - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs b/14_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs deleted file mode 100644 index 1a3902a3b..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs +++ /dev/null @@ -1,145 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/exception/asynchronous.rs"] -mod arch_exception_async; -pub use arch_exception_async::*; - -use core::{fmt, marker::PhantomData}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Interrupt descriptor. -#[derive(Copy, Clone)] -pub struct IRQDescriptor { - /// Descriptive name. - pub name: &'static str, - - /// Reference to handler trait object. - pub handler: &'static (dyn interface::IRQHandler + Sync), -} - -/// IRQContext token. -/// -/// An instance of this type indicates that the local core is currently executing in IRQ -/// context, aka executing an interrupt vector or subcalls of it. -/// -/// Concept and implementation derived from the `CriticalSection` introduced in -/// https://github.com/rust-embedded/bare-metal -#[derive(Clone, Copy)] -pub struct IRQContext<'irq_context> { - _0: PhantomData<&'irq_context ()>, -} - -/// Asynchronous exception handling interfaces. -pub mod interface { - - /// Implemented by types that handle IRQs. - pub trait IRQHandler { - /// Called when the corresponding interrupt is asserted. - fn handle(&self) -> Result<(), &'static str>; - } - - /// IRQ management functions. - /// - /// The `BSP` is supposed to supply one global instance. Typically implemented by the - /// platform's interrupt controller. - pub trait IRQManager { - /// The IRQ number type depends on the implementation. - type IRQNumberType; - - /// Register a handler. - fn register_handler( - &self, - irq_number: Self::IRQNumberType, - descriptor: super::IRQDescriptor, - ) -> Result<(), &'static str>; - - /// Enable an interrupt in the controller. - fn enable(&self, irq_number: Self::IRQNumberType); - - /// Handle pending interrupts. - /// - /// This function is called directly from the CPU's IRQ exception vector. On AArch64, - /// this means that the respective CPU core has disabled exception handling. - /// This function can therefore not be preempted and runs start to finish. - /// - /// Takes an IRQContext token to ensure it can only be called from IRQ context. - #[allow(clippy::trivially_copy_pass_by_ref)] - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - ic: &super::IRQContext<'irq_context>, - ); - - /// Print list of registered handlers. - fn print_handler(&self); - } -} - -/// A wrapper type for IRQ numbers with integrated range sanity check. -#[derive(Copy, Clone)] -pub struct IRQNumber(usize); - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl<'irq_context> IRQContext<'irq_context> { - /// Creates an IRQContext token. - /// - /// # Safety - /// - /// - This must only be called when the current core is in an interrupt context and will not - /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For - /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. - /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code - /// must not be able to influence the lifetime picked for this type, since that might cause it - /// to be inferred to `'static`. - #[inline(always)] - pub unsafe fn new() -> Self { - IRQContext { _0: PhantomData } - } -} - -impl IRQNumber<{ MAX_INCLUSIVE }> { - /// Creates a new instance if number <= MAX_INCLUSIVE. - pub const fn new(number: usize) -> Self { - assert!(number <= MAX_INCLUSIVE); - - Self { 0: number } - } - - /// Return the wrapped number. - pub fn get(self) -> usize { - self.0 - } -} - -impl fmt::Display for IRQNumber<{ MAX_INCLUSIVE }> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -/// Executes the provided closure while IRQs are masked on the executing core. -/// -/// While the function temporarily changes the HW state of the executing core, it restores it to the -/// previous state before returning, so this is deemed safe. -#[inline(always)] -pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { - let ret: T; - - unsafe { - let saved = local_irq_mask_save(); - ret = f(); - local_irq_restore(saved); - } - - ret -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/lib.rs b/14_exceptions_part2_peripheral_IRQs/src/lib.rs deleted file mode 100644 index 100ed3f13..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/lib.rs +++ /dev/null @@ -1,178 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` library. -//! -//! Used by `main.rs` to compose the final kernel binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`bsp::exception::asynchronous::irq_manager()`] - Returns a reference to the kernel's [IRQ -//! Handling interface]. -//! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. -//! - [`state::state_manager()`] - Returns a reference to the kernel's [state management] instance. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [IRQ Handling interface]: ../libkernel/exception/asynchronous/interface/trait.IRQManager.html -//! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html -//! [state management]: ../libkernel/state/struct.StateManager.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![allow(incomplete_features)] -#![feature(asm)] -#![feature(const_fn_fn_ptr_basics)] -#![feature(const_generics)] -#![feature(const_panic)] -#![feature(core_intrinsics)] -#![feature(format_args_nl)] -#![feature(global_asm)] -#![feature(linkage)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_std] -// Testing -#![cfg_attr(test, no_main)] -#![feature(custom_test_frameworks)] -#![reexport_test_harness_main = "test_main"] -#![test_runner(crate::test_runner)] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()` (defined in `main.rs`). - -mod panic_wait; -mod runtime_init; -mod synchronization; - -pub mod bsp; -pub mod console; -pub mod cpu; -pub mod driver; -pub mod exception; -pub mod memory; -pub mod print; -pub mod state; -pub mod time; - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// The default runner for unit tests. -pub fn test_runner(tests: &[&test_types::UnitTest]) { - println!("Running {} tests", tests.len()); - println!("-------------------------------------------------------------------\n"); - for (i, test) in tests.iter().enumerate() { - print!("{:>3}. {:.<58}", i + 1, test.name); - - // Run the actual test. - (test.test_func)(); - - // Failed tests call panic!(). Execution reaches here only if the test has passed. - println!("[ok]") - } -} - -/// The `kernel_init()` for unit tests. Called from `runtime_init()`. -#[cfg(test)] -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - test_main(); - - cpu::qemu_exit_success() -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/main.rs b/14_exceptions_part2_peripheral_IRQs/src/main.rs deleted file mode 100644 index 737796134..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/main.rs +++ /dev/null @@ -1,97 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -use libkernel::{bsp, cpu, driver, exception, info, memory, state, time, warn}; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order: -/// - Virtual memory must be activated before the device drivers. -/// - Without it, any atomic operations, e.g. the yet-to-be-introduced spinlocks in the device -/// drivers (which currently employ IRQSafeNullLocks instead of spinlocks), will fail to -/// work on the RPi SoCs. -#[no_mangle] -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - use memory::mmu::interface::MMU; - - exception::handling_init(); - - if let Err(string) = memory::mmu::mmu().init() { - panic!("MMU: {}", string); - } - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - bsp::driver::driver_manager().post_device_driver_init(); - // println! is usable from here on. - - // Let device drivers register and enable their handlers with the interrupt controller. - for i in bsp::driver::driver_manager().all_device_drivers() { - if let Err(msg) = i.register_and_enable_irq_handler() { - warn!("Error registering IRQ handler: {}", msg); - } - } - - // Unmask interrupts on the boot CPU core. - exception::asynchronous::local_irq_unmask(); - - // Announce conclusion of the kernel_init() phase. - state::state_manager().transition_to_single_core_main(); - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use driver::interface::DriverManager; - use exception::asynchronous::interface::IRQManager; - - info!("Booting on: {}", bsp::board_name()); - - info!("MMU online. Special regions:"); - bsp::memory::mmu::virt_mem_layout().print_layout(); - - let (_, privilege_level) = exception::current_privilege_level(); - info!("Current privilege level: {}", privilege_level); - - info!("Exception handling state:"); - exception::asynchronous::print_state(); - - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() - ); - - info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } - - info!("Registered IRQ handlers:"); - bsp::exception::asynchronous::irq_manager().print_handler(); - - info!("Echoing input now"); - cpu::wait_forever(); -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/memory.rs b/14_exceptions_part2_peripheral_IRQs/src/memory.rs deleted file mode 100644 index 32353d4f6..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/memory.rs +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -pub mod mmu; - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check `zero_volatile()`. - #[kernel_test] - fn zero_volatile_works() { - let mut x: [usize; 3] = [10, 11, 12]; - let x_range = x.as_mut_ptr_range(); - let x_range_inclusive = - RangeInclusive::new(x_range.start, unsafe { x_range.end.offset(-1) }); - - unsafe { zero_volatile(x_range_inclusive) }; - - assert_eq!(x, [0, 0, 0]); - } - - /// Check `bss` section layout. - #[kernel_test] - fn bss_section_is_sane() { - use crate::bsp::memory::bss_range_inclusive; - use core::mem; - - let start = *bss_range_inclusive().start() as usize; - let end = *bss_range_inclusive().end() as usize; - - assert_eq!(start % mem::size_of::(), 0); - assert_eq!(end % mem::size_of::(), 0); - assert!(end >= start); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs b/14_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs deleted file mode 100644 index 39f3ef3cd..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs +++ /dev/null @@ -1,204 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Memory Management Unit. -//! -//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file -//! provides types for composing an architecture-agnostic description of the kernel 's virtual -//! memory layout. -//! -//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` -//! function. -//! -//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and -//! install respective translation tables. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/memory/mmu.rs"] -mod arch_mmu; -pub use arch_mmu::*; - -use core::{fmt, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Memory Management interfaces. -pub mod interface { - - /// MMU functions. - pub trait MMU { - /// Called by the kernel during early init. Supposed to take the translation tables from the - /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. - /// - /// # Safety - /// - /// - Changes the HW's global state. - unsafe fn init(&self) -> Result<(), &'static str>; - } -} - -/// Architecture agnostic translation types. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum Translation { - Identity, - Offset(usize), -} - -/// Architecture agnostic memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum MemAttributes { - CacheableDRAM, - Device, -} - -/// Architecture agnostic access permissions. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum AccessPermissions { - ReadOnly, - ReadWrite, -} - -/// Collection of memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub struct AttributeFields { - pub mem_attributes: MemAttributes, - pub acc_perms: AccessPermissions, - pub execute_never: bool, -} - -/// Architecture agnostic descriptor for a memory range. -#[allow(missing_docs)] -pub struct TranslationDescriptor { - pub name: &'static str, - pub virtual_range: fn() -> RangeInclusive, - pub physical_range_translation: Translation, - pub attribute_fields: AttributeFields, -} - -/// Type for expressing the kernel's virtual memory layout. -pub struct KernelVirtualLayout { - /// The last (inclusive) address of the address space. - max_virt_addr_inclusive: usize, - - /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. - inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl Default for AttributeFields { - fn default() -> AttributeFields { - AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - } - } -} - -/// Human-readable output of a TranslationDescriptor. -impl fmt::Display for TranslationDescriptor { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Call the function to which self.range points, and dereference the result, which causes - // Rust to copy the value. - let start = *(self.virtual_range)().start(); - let end = *(self.virtual_range)().end(); - let size = end - start + 1; - - // log2(1024). - const KIB_RSHIFT: u32 = 10; - - // log2(1024 * 1024). - const MIB_RSHIFT: u32 = 20; - - let (size, unit) = if (size >> MIB_RSHIFT) > 0 { - (size >> MIB_RSHIFT, "MiB") - } else if (size >> KIB_RSHIFT) > 0 { - (size >> KIB_RSHIFT, "KiB") - } else { - (size, "Byte") - }; - - let attr = match self.attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => "C", - MemAttributes::Device => "Dev", - }; - - let acc_p = match self.attribute_fields.acc_perms { - AccessPermissions::ReadOnly => "RO", - AccessPermissions::ReadWrite => "RW", - }; - - let xn = if self.attribute_fields.execute_never { - "PXN" - } else { - "PX" - }; - - write!( - f, - " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", - start, end, size, unit, attr, acc_p, xn, self.name - ) - } -} - -impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { - /// Create a new instance. - pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { - Self { - max_virt_addr_inclusive: max, - inner: layout, - } - } - - /// For a virtual address, find and return the physical output address and corresponding - /// attributes. - /// - /// If the address is not found in `inner`, return an identity mapped default with normal - /// cacheable DRAM attributes. - pub fn virt_addr_properties( - &self, - virt_addr: usize, - ) -> Result<(usize, AttributeFields), &'static str> { - if virt_addr > self.max_virt_addr_inclusive { - return Err("Address out of range"); - } - - for i in self.inner.iter() { - if (i.virtual_range)().contains(&virt_addr) { - let output_addr = match i.physical_range_translation { - Translation::Identity => virt_addr, - Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), - }; - - return Ok((output_addr, i.attribute_fields)); - } - } - - Ok((virt_addr, AttributeFields::default())) - } - - /// Print the memory layout. - pub fn print_layout(&self) { - use crate::info; - - for i in self.inner.iter() { - info!("{}", i); - } - } - - #[cfg(test)] - pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { - &self.inner - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/panic_wait.rs b/14_exceptions_part2_peripheral_IRQs/src/panic_wait.rs deleted file mode 100644 index 52a89d172..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/panic_wait.rs +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu, exception}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// The point of exit for the "standard" (non-testing) `libkernel`. -/// -/// This code will be used by the release kernel binary and the `integration tests`. It is linked -/// weakly, so that the integration tests can overload it to exit `QEMU` instead of spinning -/// forever. -/// -/// This is one possible approach to solve the problem that `cargo` can not know who the consumer of -/// the library will be: -/// - The release kernel binary that should safely park the paniced core, -/// - or an `integration test` that is executed in QEMU, which should just exit QEMU. -#[cfg(not(test))] -#[linkage = "weak"] -#[no_mangle] -fn _panic_exit() -> ! { - cpu::wait_forever() -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - unsafe { exception::asynchronous::local_irq_mask() }; - - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - _panic_exit() -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// The point of exit when the library is compiled for testing. -#[cfg(test)] -#[no_mangle] -fn _panic_exit() -> ! { - cpu::qemu_exit_failure() -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/print.rs b/14_exceptions_part2_peripheral_IRQs/src/print.rs deleted file mode 100644 index 8b6f3f988..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/print.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} - -/// Prints an info, with a newline. -#[macro_export] -macro_rules! info { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} - -/// Prints a warning, with a newline. -#[macro_export] -macro_rules! warn { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/runtime_init.rs b/14_exceptions_part2_peripheral_IRQs/src/runtime_init.rs deleted file mode 100644 index 1306578dd..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/runtime_init.rs +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - extern "Rust" { - fn kernel_init() -> !; - } - - zero_bss(); - kernel_init() -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/state.rs b/14_exceptions_part2_peripheral_IRQs/src/state.rs deleted file mode 100644 index af1d93482..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/state.rs +++ /dev/null @@ -1,92 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! State information about the kernel itself. - -use core::sync::atomic::{AtomicU8, Ordering}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Different stages in the kernel execution. -#[derive(Copy, Clone, Eq, PartialEq)] -enum State { - /// The kernel starts booting in this state. - Init, - - /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of - /// `kernel_init()`, after all init calls are done). - SingleCoreMain, - - /// The kernel transitions to this state when it boots the secondary cores, aka switches - /// exectution mode to symmetric multiprocessing (SMP). - MultiCoreMain, -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Maintains the kernel state and state transitions. -pub struct StateManager(AtomicU8); - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static STATE_MANAGER: StateManager = StateManager::new(); - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the global StateManager. -pub fn state_manager() -> &'static StateManager { - &STATE_MANAGER -} - -impl StateManager { - const INIT: u8 = 0; - const SINGLE_CORE_MAIN: u8 = 1; - const MULTI_CORE_MAIN: u8 = 2; - - /// Create a new instance. - pub const fn new() -> Self { - Self(AtomicU8::new(Self::INIT)) - } - - /// Return the current state. - fn state(&self) -> State { - let state = self.0.load(Ordering::Acquire); - - match state { - Self::INIT => State::Init, - Self::SINGLE_CORE_MAIN => State::SingleCoreMain, - Self::MULTI_CORE_MAIN => State::MultiCoreMain, - _ => panic!("Invalid KERNEL_STATE"), - } - } - - /// Return if the kernel is still in an init state. - pub fn is_init(&self) -> bool { - self.state() == State::Init - } - - /// Transition from Init to SingleCoreMain. - pub fn transition_to_single_core_main(&self) { - if self - .0 - .compare_exchange( - Self::INIT, - Self::SINGLE_CORE_MAIN, - Ordering::Acquire, - Ordering::Relaxed, - ) - .is_err() - { - panic!("transition_to_single_core_main() called while state != Init"); - } - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/synchronization.rs b/14_exceptions_part2_peripheral_IRQs/src/synchronization.rs deleted file mode 100644 index 039df47a4..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/synchronization.rs +++ /dev/null @@ -1,140 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } - - /// A reader-writer exclusion type. - /// - /// The implementing object allows either a number of readers or at most one writer at any point - /// in time. - pub trait ReadWriteEx { - /// The type of encapsulated data. - type Data; - - /// Grants temporary mutable access to the encapsulated data. - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - - /// Grants temporary immutable access to the encapsulated data. - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing on a single core. -pub struct IRQSafeNullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. -/// -/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. -pub struct InitStateLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} -unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} - -impl IRQSafeNullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -unsafe impl Send for InitStateLock where T: ?Sized + Send {} -unsafe impl Sync for InitStateLock where T: ?Sized + Send {} - -impl InitStateLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use crate::{exception, state}; - -impl interface::Mutex for IRQSafeNullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - // Execute the closure while IRQs are masked. - exception::asynchronous::exec_with_irq_masked(|| f(data)) - } -} - -impl interface::ReadWriteEx for InitStateLock { - type Data = T; - - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - assert!( - state::state_manager().is_init(), - "InitStateLock::write called after kernel init phase" - ); - assert!( - !exception::asynchronous::is_local_irq_masked(), - "InitStateLock::write called with IRQs unmasked" - ); - - let data = unsafe { &mut *self.data.get() }; - - f(data) - } - - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { - let data = unsafe { &*self.data.get() }; - - f(data) - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/src/time.rs b/14_exceptions_part2_peripheral_IRQs/src/time.rs deleted file mode 100644 index cd3ceec33..000000000 --- a/14_exceptions_part2_peripheral_IRQs/src/time.rs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; -pub use arch_time::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); - } -} diff --git a/14_exceptions_part2_peripheral_IRQs/test-macros/Cargo.toml b/14_exceptions_part2_peripheral_IRQs/test-macros/Cargo.toml deleted file mode 100644 index a570f72b4..000000000 --- a/14_exceptions_part2_peripheral_IRQs/test-macros/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "test-macros" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1.x" -quote = "1.x" -syn = { version = "1.x", features = ["full"] } -test-types = { path = "../test-types" } diff --git a/14_exceptions_part2_peripheral_IRQs/test-macros/src/lib.rs b/14_exceptions_part2_peripheral_IRQs/test-macros/src/lib.rs deleted file mode 100644 index 092c4806e..000000000 --- a/14_exceptions_part2_peripheral_IRQs/test-macros/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -use proc_macro::TokenStream; -use proc_macro2::Span; -use quote::quote; -use syn::{parse_macro_input, Ident, ItemFn}; - -#[proc_macro_attribute] -pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { - let f = parse_macro_input!(input as ItemFn); - - let test_name = &format!("{}", f.sig.ident.to_string()); - let test_ident = Ident::new( - &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), - Span::call_site(), - ); - let test_code_block = f.block; - - quote!( - #[test_case] - const #test_ident: test_types::UnitTest = test_types::UnitTest { - name: #test_name, - test_func: || #test_code_block, - }; - ) - .into() -} diff --git a/14_exceptions_part2_peripheral_IRQs/test-types/Cargo.toml b/14_exceptions_part2_peripheral_IRQs/test-types/Cargo.toml deleted file mode 100644 index a0be2c57c..000000000 --- a/14_exceptions_part2_peripheral_IRQs/test-types/Cargo.toml +++ /dev/null @@ -1,5 +0,0 @@ -[package] -name = "test-types" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" diff --git a/14_exceptions_part2_peripheral_IRQs/test-types/src/lib.rs b/14_exceptions_part2_peripheral_IRQs/test-types/src/lib.rs deleted file mode 100644 index 371bb5574..000000000 --- a/14_exceptions_part2_peripheral_IRQs/test-types/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Types for the `custom_test_frameworks` implementation. - -#![no_std] - -/// Unit test container. -pub struct UnitTest { - /// Name of the test. - pub name: &'static str, - - /// Function pointer to the test. - pub test_func: fn(), -} diff --git a/14_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rb b/14_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rb deleted file mode 100644 index a6b549b2a..000000000 --- a/14_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rb +++ /dev/null @@ -1,50 +0,0 @@ -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2019-2020 Andre Richter - -require 'expect' - -TIMEOUT_SECS = 3 - -# Verify sending and receiving works as expected. -class TxRxHandshake - def name - 'Transmit and Receive handshake' - end - - def run(qemu_out, qemu_in) - qemu_in.write_nonblock('ABC') - raise('TX/RX test failed') if qemu_out.expect('OK1234', TIMEOUT_SECS).nil? - end -end - -# Check for correct TX statistics implementation. Depends on test 1 being run first. -class TxStatistics - def name - 'Transmit statistics' - end - - def run(qemu_out, _qemu_in) - raise('chars_written reported wrong') if qemu_out.expect('6', TIMEOUT_SECS).nil? - end -end - -# Check for correct RX statistics implementation. Depends on test 1 being run first. -class RxStatistics - def name - 'Receive statistics' - end - - def run(qemu_out, _qemu_in) - raise('chars_read reported wrong') if qemu_out.expect('3', TIMEOUT_SECS).nil? - end -end - -##-------------------------------------------------------------------------------------------------- -## Test registration -##-------------------------------------------------------------------------------------------------- -def subtest_collection - [TxRxHandshake.new, TxStatistics.new, RxStatistics.new] -end diff --git a/14_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rs b/14_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rs deleted file mode 100644 index 5aa38f098..000000000 --- a/14_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rs +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Console sanity tests - RX, TX and statistics. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -mod panic_exit_failure; - -use libkernel::{bsp, console, print}; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - use bsp::console::{console, qemu_bring_up_console}; - use console::interface::*; - - qemu_bring_up_console(); - - // Handshake - assert_eq!(console().read_char(), 'A'); - assert_eq!(console().read_char(), 'B'); - assert_eq!(console().read_char(), 'C'); - print!("OK1234"); - - // 6 - print!("{}", console().chars_written()); - - // 3 - print!("{}", console().chars_read()); - - // The QEMU process running this test will be closed by the I/O test harness. - loop {} -} diff --git a/14_exceptions_part2_peripheral_IRQs/tests/01_timer_sanity.rs b/14_exceptions_part2_peripheral_IRQs/tests/01_timer_sanity.rs deleted file mode 100644 index e0b3c1622..000000000 --- a/14_exceptions_part2_peripheral_IRQs/tests/01_timer_sanity.rs +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Timer sanity tests. - -#![feature(custom_test_frameworks)] -#![no_main] -#![no_std] -#![reexport_test_harness_main = "test_main"] -#![test_runner(libkernel::test_runner)] - -mod panic_exit_failure; - -use core::time::Duration; -use libkernel::{bsp, cpu, time, time::interface::TimeManager}; -use test_macros::kernel_test; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. - - test_main(); - - cpu::qemu_exit_success() -} - -/// Simple check that the timer is running. -#[kernel_test] -fn timer_is_counting() { - assert!(time::time_manager().uptime().as_nanos() > 0) -} - -/// Timer resolution must be sufficient. -#[kernel_test] -fn timer_resolution_is_sufficient() { - assert!(time::time_manager().resolution().as_nanos() < 100) -} - -/// Sanity check spin_for() implementation. -#[kernel_test] -fn spin_accuracy_check_1_second() { - let t1 = time::time_manager().uptime(); - time::time_manager().spin_for(Duration::from_secs(1)); - let t2 = time::time_manager().uptime(); - - assert_eq!((t2 - t1).as_secs(), 1) -} diff --git a/14_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs b/14_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs deleted file mode 100644 index 64fc5486e..000000000 --- a/14_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Page faults must result in synchronous exceptions. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -/// -/// Reaching this code is a success, because it is called from the synchronous exception handler, -/// which is what this test wants to achieve. -/// -/// It also means that this integration test can not use any other code that calls panic!() directly -/// or indirectly. -mod panic_exit_success; - -use libkernel::{bsp, cpu, exception, memory, println}; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - use memory::mmu::interface::MMU; - - bsp::console::qemu_bring_up_console(); - - println!("Testing synchronous exception handling by causing a page fault"); - println!("-------------------------------------------------------------------\n"); - - exception::handling_init(); - - if let Err(string) = memory::mmu::mmu().init() { - println!("MMU: {}", string); - cpu::qemu_exit_failure() - } - - println!("Writing beyond mapped area to address 9 GiB..."); - let big_addr: u64 = 9 * 1024 * 1024 * 1024; - core::ptr::read_volatile(big_addr as *mut u64); - - // If execution reaches here, the memory access above did not cause a page fault exception. - cpu::qemu_exit_failure() -} diff --git a/14_exceptions_part2_peripheral_IRQs/tests/03_exception_irq_sanity.rs b/14_exceptions_part2_peripheral_IRQs/tests/03_exception_irq_sanity.rs deleted file mode 100644 index 6e2ae8f7c..000000000 --- a/14_exceptions_part2_peripheral_IRQs/tests/03_exception_irq_sanity.rs +++ /dev/null @@ -1,68 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! IRQ handling sanity tests. - -#![feature(custom_test_frameworks)] -#![no_main] -#![no_std] -#![reexport_test_harness_main = "test_main"] -#![test_runner(libkernel::test_runner)] - -mod panic_exit_failure; - -use libkernel::{bsp, cpu, exception}; -use test_macros::kernel_test; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - exception::handling_init(); - exception::asynchronous::local_irq_unmask(); - - test_main(); - - cpu::qemu_exit_success() -} - -/// Check that IRQ masking works. -#[kernel_test] -fn local_irq_mask_works() { - // Precondition: IRQs are unmasked. - assert!(exception::asynchronous::is_local_irq_masked()); - - unsafe { exception::asynchronous::local_irq_mask() }; - assert!(!exception::asynchronous::is_local_irq_masked()); - - // Restore earlier state. - unsafe { exception::asynchronous::local_irq_unmask() }; -} - -/// Check that IRQ unmasking works. -#[kernel_test] -fn local_irq_unmask_works() { - // Precondition: IRQs are masked. - unsafe { exception::asynchronous::local_irq_mask() }; - assert!(!exception::asynchronous::is_local_irq_masked()); - - unsafe { exception::asynchronous::local_irq_unmask() }; - assert!(exception::asynchronous::is_local_irq_masked()); -} - -/// Check that IRQ mask save is saving "something". -#[kernel_test] -fn local_irq_mask_save_works() { - // Precondition: IRQs are unmasked. - assert!(exception::asynchronous::is_local_irq_masked()); - - let first = unsafe { exception::asynchronous::local_irq_mask_save() }; - assert!(!exception::asynchronous::is_local_irq_masked()); - - let second = unsafe { exception::asynchronous::local_irq_mask_save() }; - assert_ne!(first, second); - - unsafe { exception::asynchronous::local_irq_restore(first) }; - assert!(exception::asynchronous::is_local_irq_masked()); -} diff --git a/14_exceptions_part2_peripheral_IRQs/tests/panic_exit_failure/mod.rs b/14_exceptions_part2_peripheral_IRQs/tests/panic_exit_failure/mod.rs deleted file mode 100644 index b4ac73d1e..000000000 --- a/14_exceptions_part2_peripheral_IRQs/tests/panic_exit_failure/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -#[no_mangle] -fn _panic_exit() -> ! { - libkernel::cpu::qemu_exit_failure() -} diff --git a/14_exceptions_part2_peripheral_IRQs/tests/panic_exit_success/mod.rs b/14_exceptions_part2_peripheral_IRQs/tests/panic_exit_success/mod.rs deleted file mode 100644 index 54bb072d7..000000000 --- a/14_exceptions_part2_peripheral_IRQs/tests/panic_exit_success/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -#[no_mangle] -fn _panic_exit() -> ! { - libkernel::cpu::qemu_exit_success() -} diff --git a/14_exceptions_part2_peripheral_IRQs/tests/runner.rb b/14_exceptions_part2_peripheral_IRQs/tests/runner.rb deleted file mode 100755 index 2a0aa393e..000000000 --- a/14_exceptions_part2_peripheral_IRQs/tests/runner.rb +++ /dev/null @@ -1,143 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2019-2020 Andre Richter - -require 'English' -require 'pty' - -# Test base class. -class Test - INDENT = ' ' - - def print_border(status) - puts - puts "#{INDENT}-------------------------------------------------------------------" - puts status - puts "#{INDENT}-------------------------------------------------------------------\n\n\n" - end - - def print_error(error) - puts - print_border("#{INDENT}❌ Failure: #{error}: #{@test_name}") - end - - def print_success - print_border("#{INDENT}✅ Success: #{@test_name}") - end - - def print_output - puts "#{INDENT}-------------------------------------------------------------------" - print INDENT - print '🦀 ' - print @output.join.gsub("\n", "\n#{INDENT}") - end - - def finish(error) - print_output - - exit_code = if error - print_error(error) - false - else - print_success - true - end - - exit(exit_code) - end -end - -# Executes tests with console I/O. -class ConsoleTest < Test - def initialize(binary, qemu_cmd, test_name, console_subtests) - super() - - @binary = binary - @qemu_cmd = qemu_cmd - @test_name = test_name - @console_subtests = console_subtests - @cur_subtest = 1 - @output = ["Running #{@console_subtests.length} console-based tests\n", - "-------------------------------------------------------------------\n\n"] - end - - def format_test_name(number, name) - formatted_name = "#{number.to_s.rjust(3)}. #{name}" - formatted_name.ljust(63, '.') - end - - def run_subtest(subtest, qemu_out, qemu_in) - @output << format_test_name(@cur_subtest, subtest.name) - - subtest.run(qemu_out, qemu_in) - - @output << "[ok]\n" - @cur_subtest += 1 - end - - def exec - error = false - - PTY.spawn(@qemu_cmd) do |qemu_out, qemu_in| - begin - @console_subtests.each { |t| run_subtest(t, qemu_out, qemu_in) } - rescue StandardError => e - error = e.message - end - - finish(error) - end - end -end - -# A wrapper around the bare QEMU invocation. -class RawTest < Test - MAX_WAIT_SECS = 5 - - def initialize(binary, qemu_cmd, test_name) - super() - - @binary = binary - @qemu_cmd = qemu_cmd - @test_name = test_name - @output = [] - end - - def exec - error = 'Timed out waiting for test' - io = IO.popen(@qemu_cmd) - - while IO.select([io], nil, nil, MAX_WAIT_SECS) - begin - @output << io.read_nonblock(1024) - rescue EOFError - io.close - error = $CHILD_STATUS.to_i != 0 - break - end - end - - finish(error) - end -end - -##-------------------------------------------------------------------------------------------------- -## Script entry point -##-------------------------------------------------------------------------------------------------- -binary = ARGV.last -test_name = binary.gsub(%r{.*deps/}, '').split('-')[0] -console_test_file = "tests/#{test_name}.rb" -qemu_cmd = ARGV.join(' ') - -test_runner = if File.exist?(console_test_file) - load console_test_file - # subtest_collection is provided by console_test_file - ConsoleTest.new(binary, qemu_cmd, test_name, subtest_collection) - else - RawTest.new(binary, qemu_cmd, test_name) - end - -test_runner.exec diff --git a/15_virtual_mem_part2_mmio_remap/.cargo/config.toml b/14_virtual_mem_part2_mmio_remap/.cargo/config.toml similarity index 100% rename from 15_virtual_mem_part2_mmio_remap/.cargo/config.toml rename to 14_virtual_mem_part2_mmio_remap/.cargo/config.toml diff --git a/14_virtual_mem_part2_mmio_remap/.vscode/settings.json b/14_virtual_mem_part2_mmio_remap/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/14_virtual_mem_part2_mmio_remap/Cargo.lock b/14_virtual_mem_part2_mmio_remap/Cargo.lock new file mode 100644 index 000000000..eea037346 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/Cargo.lock @@ -0,0 +1,84 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.14.0" +dependencies = [ + "aarch64-cpu", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/14_virtual_mem_part2_mmio_remap/Cargo.toml b/14_virtual_mem_part2_mmio_remap/Cargo.toml new file mode 100644 index 000000000..6480a7276 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +members = [ + "libraries/*", + "kernel" +] + +[profile.release] +lto = true diff --git a/14_virtual_mem_part2_mmio_remap/Makefile b/14_virtual_mem_part2_mmio_remap/Makefile new file mode 100644 index 000000000..4e2efeff3 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/Makefile @@ -0,0 +1,334 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/14_virtual_mem_part2_mmio_remap/README.md b/14_virtual_mem_part2_mmio_remap/README.md new file mode 100644 index 000000000..e21ad5017 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/README.md @@ -0,0 +1,3451 @@ +# Tutorial 14 - Virtual Memory Part 2: MMIO Remap + +## tl;dr + +- We introduce a first set of changes which is eventually needed for separating `kernel` and `user` + address spaces. +- The memory mapping strategy gets more sophisticated as we do away with `identity mapping` the + whole of the board's address space. +- Instead, only ranges that are actually needed are mapped: + - The `kernel binary` stays `identity mapped` for now. + - Device `MMIO regions` are remapped lazily (to a special reserved virtual address region). + +## Table of Contents + +- [Introduction](#introduction) +- [Implementation](#implementation) + - [A New Mapping API in `src/memory/mmu.rs`](#a-new-mapping-api-in-srcmemorymmutranslationtablers) + - [The new APIs in action](#the-new-apis-in-action) + - [MMIO Virtual Address Allocation](#mmio-virtual-address-allocation) + - [Supporting Changes](#supporting-changes) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +This tutorial is a first step of many needed for enabling `userspace applications` (which we +hopefully will have some day in the very distant future). + +For this, one of the features we want is a clean separation of `kernel` and `user` address spaces. +Fortunately, `ARMv8` has convenient architecture support to realize this. The following text and +pictue gives some more motivation and technical information. It is quoted from the _[ARM Cortex-A +Series Programmer’s Guide for ARMv8-A], Chapter 12.2, Separation of kernel and application Virtual +Address spaces_: + +> Operating systems typically have a number of applications or tasks running concurrently. Each of +> these has its own unique set of translation tables and the kernel switches from one to another as +> part of the process of switching context between one task and another. However, much of the memory +> system is used only by the kernel and has fixed virtual to Physical Address mappings where the +> translation table entries rarely change. The ARMv8 architecture provides a number of features to +> efficiently handle this requirement. +> +> The table base addresses are specified in the Translation Table Base Registers `TTBR0_EL1` and +> `TTBR1_EL1`. The translation table pointed to by `TTBR0` is selected when the upper bits of the VA +> are all 0. `TTBR1` is selected when the upper bits of the VA are all set to 1. [...] +> +> Figure 12-4 shows how the kernel space can be mapped to the most significant area of memory and +> the Virtual Address space associated with each application mapped to the least significant area of +> memory. However, both of these are mapped to a much smaller Physical Address space. + +

+ +

+ +This approach is also sometimes called a "[higher half kernel]". To eventually achieve this +separation, this tutorial makes a start by changing the following things: + +1. Instead of bulk-`identity mapping` the whole of the board's address space, only the particular + parts that are needed will be mapped. +1. For now, the `kernel binary` stays identity mapped. This will be changed in the coming tutorials + as it is a quite difficult and peculiar exercise to remap the kernel. +1. Device `MMIO regions` are lazily remapped during device driver bringup (using the new + `DriverManage` function `instantiate_drivers()`). + 1. A dedicated region of virtual addresses that we reserve using `BSP` code and the `linker + script` is used for this. +1. We keep using `TTBR0` for the kernel translation tables for now. This will be changed when we + remap the `kernel binary` in the coming tutorials. + +[ARM Cortex-A Series Programmer’s Guide for ARMv8-A]: https://developer.arm.com/documentation/den0024/latest/ +[higher half kernel]: https://wiki.osdev.org/Higher_Half_Kernel + +## Implementation + +Until now, the whole address space of the board was identity mapped at once. The **architecture** +(`src/_arch/_/memory/**`) and **bsp** (`src/bsp/_/memory/**`) parts of the kernel worked +together directly while setting up the translation tables, without any indirection through **generic +kernel code** (`src/memory/**`). + +The way it worked was that the `architectural MMU code` would query the `bsp code` about the start +and end of the physical address space, and any special regions in this space that need a mapping +that _is not_ normal chacheable DRAM. It would then go ahead and map the whole address space at once +and never touch the translation tables again during runtime. + +Changing in this tutorial, **architecture** and **bsp** code will no longer autonomously create the +virtual memory mappings. Instead, this is now orchestrated by the kernel's **generic MMU subsystem +code**. + +### A New Mapping API in `src/memory/mmu/translation_table.rs` + +First, we define an interface for operating on `translation tables`: + +```rust +/// Translation table operations. +pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self); + + /// The translation table's base address to be used for programming the MMU. + fn phys_base_address(&self) -> Address; + + /// Map the given virtual memory region to the given physical memory region. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; +} +``` + +In order to enable the generic kernel code to manipulate the kernel's translation tables, they must +first be made accessible. Until now, they were just a "hidden" struct in the `architectural` MMU +driver (`src/arch/.../memory/mmu.rs`). This made sense because the MMU driver code was the only code +that needed to be concerned with the table data structure, so having it accessible locally +simplified things. + +Since the tables need to be exposed to the rest of the kernel code now, it makes sense to move them +to `BSP` code. Because ultimately, it is the `BSP` that is defining the translation table's +properties, such as the size of the virtual address space that the tables need to cover. + +They are now defined in the global instances region of `src/bsp/.../memory/mmu.rs`. To control +access, they are guarded by an `InitStateLock`. + +```rust +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new()); +``` + +The struct `KernelTranslationTable` is a type alias defined in the same file, which in turn gets its +definition from an associated type of type `KernelVirtAddrSpace`, which itself is a type alias of +`memory::mmu::AddressSpace`. I know this sounds horribly complicated, but in the end this is just +some layers of `const generics` whose implementation is scattered between `generic` and `arch` code. +This is done to (1) ensure a sane compile-time definition of the translation table struct (by doing +various bounds checks), and (2) to separate concerns between generic `MMU` code and specializations +that come from the `architectural` part. + +In the end, these tables can be accessed by calling `bsp::memory::mmu::kernel_translation_tables()`: + +```rust +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} +``` + +Finally, the generic kernel code (`src/memory/mmu.rs`) now provides a couple of memory mapping +functions that access and manipulate this instance. They are exported for the rest of the kernel to +use: + +```rust +/// Raw mapping of a virtual to physical region in the kernel translation tables. +/// +/// Prevents mapping into the MMIO range of the tables. +pub unsafe fn kernel_map_at( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str>; + +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str>; + +/// Map the kernel's binary. Returns the translation table's base address. +pub unsafe fn kernel_map_binary() -> Result, &'static str>; + +/// Enable the MMU and data + instruction caching. +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError>; +``` + +### The new APIs in action + +`kernel_map_binary()` and `enable_mmu_and_caching()` are used early in `kernel_init()` to set up +virtual memory: + +```rust +let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, +}; + +if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); +} +``` + +Both functions internally use `bsp` and `arch` specific code to achieve their goals. For example, +`memory::mmu::kernel_map_binary()` itself wraps around a `bsp` function of the same name +(`bsp::memory::mmu::kernel_map_binary()`): + +```rust +/// Map the kernel binary. +pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { + generic_mmu::kernel_map_at( + "Kernel boot-core stack", + // omitted for brevity. + )?; + + generic_mmu::kernel_map_at( + "Kernel code and RO data", + &virt_code_region(), + &kernel_virt_to_phys_region(virt_code_region()), + &AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadOnly, + execute_never: false, + }, + )?; + + generic_mmu::kernel_map_at( + "Kernel data and bss", + // omitted for brevity. + )?; + + Ok(()) +} +``` + +Another user of the new APIs is the **driver subsystem**. As has been said in the introduction, the +goal is to remap the `MMIO` regions of the drivers. To achieve this in a seamless way, some changes +to the architecture of the driver subsystem were needed. + +Until now, the drivers were `static instances` which had their `MMIO addresses` statically set in +the constructor. This was fine, because even if virtual memory was activated, only `identity +mapping` was used, so the hardcoded addresses would be valid with and without the MMU being active. + +With `remapped MMIO addresses`, this is not possible anymore, since the remapping will only happen +at runtime. Therefore, the new approach is to defer the whole instantiation of the drivers until the +remapped addresses are known. To achieve this, in `src/bsp/raspberrypi/drivers.rs`, the static +driver instances are now wrapped into a `MaybeUninit` (and are also `mut` now): + +```rust +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi3")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi4")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); +``` + +Accordingly, new dedicated `instantiate_xyz()` functions have been added, which will be called by +the corresponding `driver_xyz()` functions. Here is an example for the `UART`: + +```rust +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} +``` + +```rust +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} +``` + +The code shows that an `MMIODescriptor` is created first, and then used to remap the MMIO region +using `memory::mmu::kernel_map_mmio()`. This function will be discussed in detail in the next +chapter. What's important for now is that it returns the new `Virtual Address` of the remapped MMIO +region. The constructor of the `UART` driver now also expects a virtual address. + +Next, a new instance of the `PL011Uart` driver is created, and written into the `PL011_UART` global +variable (remember, it is defined as `MaybeUninit = +MaybeUninit::uninit()`). Meaning, after this line of code, `PL011_UART` is properly initialized. +Only then, the driver is registered with the kernel and thus becomes accessible for the first time. +This ensures that nobody can use the UART before its memory has been initialized properly. + +### MMIO Virtual Address Allocation + +Getting back to the remapping part, let's peek inside `memory::mmu::kernel_map_mmio()`. We can see +that a `virtual address region` is obtained from an `allocator` before remapping: + +```rust +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + + // omitted + + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + // omitted +} +``` + +This allocator is defined and implemented in the added file `src/memory/mmu/page_alloc.rs`. Like +other parts of the mapping code, its implementation makes use of the newly introduced +`PageAddress` and `MemoryRegion` types (in +[`src/memory/mmu/types.rs`](kernel/src/memory/mmu/types.rs)), but apart from that is rather straight +forward. Therefore, it won't be covered in details here. + +The more interesting question is: How does the allocator get to learn which VAs it can use? + +This is happening in the following function, which gets called as part of +`memory::mmu::post_enable_init()`, which in turn gets called in `kernel_init()` after the MMU has +been turned on. + +```rust +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} +``` + +Again, it is the `BSP` that provides the information. The `BSP` itself indirectly gets it from the +linker script. In it, we have defined an `8 MiB` region right after the `.data` segment: + +```ld.s +__data_end_exclusive = .; + +/*********************************************************************************************** +* MMIO Remap Reserved +***********************************************************************************************/ +__mmio_remap_start = .; +. += 8 * 1024 * 1024; +__mmio_remap_end_exclusive = .; + +ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") +``` + +The two symbols `__mmio_remap_start` and `__mmio_remap_end_exclusive` are used by the `BSP` to learn +the VA range. + +### Supporting Changes + +There's a couple of changes more not covered in this tutorial text, but the reader should ideally +skim through them: + +- [`src/memory.rs`](kernel/src/memory.rs) and + [`src/memory/mmu/types.rs`](kernel/src/memory/mmu/types.rs) introduce supporting types, + like`Address`, `PageAddress` and `MemoryRegion`. It is worth reading their + implementations. +- [`src/memory/mmu/mapping_record.rs`](kernel/src/memory/mmu/mapping_record.rs) provides the generic + kernel code's way of tracking previous memory mappings for use cases such as reusing existing + mappings (in case of drivers that have their MMIO ranges in the same `64 KiB` page) or printing + mappings statistics. + +## Test it + +When you load the kernel, you can now see that the driver's MMIO virtual addresses start right after +the `.data` section: + +Raspberry Pi 3: + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 65 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.740694] mingo version 0.14.0 +[ 0.740902] Booting on: Raspberry Pi 3 +[ 0.741357] MMU online: +[ 0.741649] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 0.743393] Virtual Physical Size Attr Entity +[ 0.745138] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 0.746883] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack +[ 0.748486] 0x0000_0000_0008_0000..0x0000_0000_0008_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data +[ 0.750099] 0x0000_0000_0009_0000..0x0000_0000_000e_ffff --> 0x00_0009_0000..0x00_000e_ffff | 384 KiB | C RW XN | Kernel data and bss +[ 0.751670] 0x0000_0000_000f_0000..0x0000_0000_000f_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART +[ 0.753187] | BCM GPIO +[ 0.754638] 0x0000_0000_0010_0000..0x0000_0000_0010_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Interrupt Controller +[ 0.756264] ------------------------------------------------------------------------------------------------------------------------------------------- +``` + +Raspberry Pi 4: + +```console +$ BSP=rpi4 make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 4 + +[ML] Requesting binary +[MP] ⏩ Pushing 65 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[ML] Loaded! Executing the payload now + +[ 0.736136] mingo version 0.14.0 +[ 0.736170] Booting on: Raspberry Pi 4 +[ 0.736625] MMU online: +[ 0.736918] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 0.738662] Virtual Physical Size Attr Entity +[ 0.740406] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 0.742151] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack +[ 0.743754] 0x0000_0000_0008_0000..0x0000_0000_0008_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data +[ 0.745368] 0x0000_0000_0009_0000..0x0000_0000_000d_ffff --> 0x00_0009_0000..0x00_000d_ffff | 320 KiB | C RW XN | Kernel data and bss +[ 0.746938] 0x0000_0000_000e_0000..0x0000_0000_000e_ffff --> 0x00_fe20_0000..0x00_fe20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART +[ 0.748455] | BCM GPIO +[ 0.749907] 0x0000_0000_000f_0000..0x0000_0000_000f_ffff --> 0x00_ff84_0000..0x00_ff84_ffff | 64 KiB | Dev RW XN | GICv2 GICD +[ 0.751380] | GICV2 GICC +[ 0.752853] ------------------------------------------------------------------------------------------------------------------------------------------- +``` + +## Diff to previous +```diff + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml +--- 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml ++++ 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.13.0" ++version = "0.14.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +@@ -14,10 +14,14 @@ + //! crate::memory::mmu::translation_table::arch_translation_table + + use crate::{ +- bsp, memory, +- memory::mmu::{ +- arch_mmu::{Granule512MiB, Granule64KiB}, +- AccessPermissions, AttributeFields, MemAttributes, ++ bsp, ++ memory::{ ++ self, ++ mmu::{ ++ arch_mmu::{Granule512MiB, Granule64KiB}, ++ AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, ++ }, ++ Address, Physical, Virtual, + }, + }; + use core::convert; +@@ -121,12 +125,9 @@ + } + + trait StartAddr { +- fn phys_start_addr_u64(&self) -> u64; +- fn phys_start_addr_usize(&self) -> usize; ++ fn phys_start_addr(&self) -> Address; + } + +-const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; +- + //-------------------------------------------------------------------------------------------------- + // Public Definitions + //-------------------------------------------------------------------------------------------------- +@@ -141,10 +142,10 @@ + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], +-} + +-/// A translation table type for the kernel space. +-pub type KernelTranslationTable = FixedSizeTranslationTable; ++ /// Have the tables been initialized? ++ initialized: bool, ++} + + //-------------------------------------------------------------------------------------------------- + // Private Code +@@ -152,12 +153,8 @@ + + // The binary is still identity mapped, so we don't need to convert here. + impl StartAddr for [T; N] { +- fn phys_start_addr_u64(&self) -> u64 { +- self as *const T as u64 +- } +- +- fn phys_start_addr_usize(&self) -> usize { +- self as *const _ as usize ++ fn phys_start_addr(&self) -> Address { ++ Address::new(self as *const _ as usize) + } + } + +@@ -170,10 +167,10 @@ + } + + /// Create an instance pointing to the supplied address. +- pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { ++ pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { + let val = InMemoryRegister::::new(0); + +- let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; ++ let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table +@@ -230,12 +227,15 @@ + } + + /// Create an instance. +- pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { ++ pub fn from_output_page_addr( ++ phys_output_page_addr: PageAddress, ++ attribute_fields: &AttributeFields, ++ ) -> Self { + let val = InMemoryRegister::::new(0); + +- let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; ++ let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; + val.write( +- STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) ++ STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True +@@ -244,50 +244,133 @@ + + Self { value: val.get() } + } ++ ++ /// Returns the valid bit. ++ fn is_valid(&self) -> bool { ++ InMemoryRegister::::new(self.value) ++ .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) ++ } + } + + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- + ++impl memory::mmu::AssociatedTranslationTable ++ for memory::mmu::AddressSpace ++where ++ [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, ++{ ++ type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }>; ++} ++ + impl FixedSizeTranslationTable { + /// Create an instance. ++ #[allow(clippy::assertions_on_constants)] + pub const fn new() -> Self { ++ assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); ++ + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], ++ initialized: false, + } + } + +- /// Iterates over all static translation table entries and fills them at once. +- /// +- /// # Safety +- /// +- /// - Modifies a `static mut`. Ensure it only happens from here. +- pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { +- for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { +- *l2_entry = +- TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); ++ /// Helper to calculate the lvl2 and lvl3 indices from an address. ++ #[inline(always)] ++ fn lvl2_lvl3_index_from_page_addr( ++ &self, ++ virt_page_addr: PageAddress, ++ ) -> Result<(usize, usize), &'static str> { ++ let addr = virt_page_addr.into_inner().as_usize(); ++ let lvl2_index = addr >> Granule512MiB::SHIFT; ++ let lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + +- for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { +- let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); ++ if lvl2_index > (NUM_TABLES - 1) { ++ return Err("Virtual page is out of bounds of translation table"); ++ } + +- let (phys_output_addr, attribute_fields) = +- bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; ++ Ok((lvl2_index, lvl3_index)) ++ } + +- *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); +- } ++ /// Sets the PageDescriptor corresponding to the supplied page address. ++ /// ++ /// Doesn't allow overriding an already valid page. ++ #[inline(always)] ++ fn set_page_descriptor_from_page_addr( ++ &mut self, ++ virt_page_addr: PageAddress, ++ new_desc: &PageDescriptor, ++ ) -> Result<(), &'static str> { ++ let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; ++ let desc = &mut self.lvl3[lvl2_index][lvl3_index]; ++ ++ if desc.is_valid() { ++ return Err("Virtual page is already mapped"); + } + ++ *desc = *new_desc; + Ok(()) + } ++} + +- /// The translation table's base address to be used for programming the MMU. +- pub fn phys_base_address(&self) -> u64 { +- self.lvl2.phys_start_addr_u64() ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++ ++impl memory::mmu::translation_table::interface::TranslationTable ++ for FixedSizeTranslationTable ++{ ++ fn init(&mut self) { ++ if self.initialized { ++ return; ++ } ++ ++ // Populate the l2 entries. ++ for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { ++ let phys_table_addr = self.lvl3[lvl2_nr].phys_start_addr(); ++ ++ let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); ++ *lvl2_entry = new_desc; ++ } ++ ++ self.initialized = true; ++ } ++ ++ fn phys_base_address(&self) -> Address { ++ self.lvl2.phys_start_addr() ++ } ++ ++ unsafe fn map_at( ++ &mut self, ++ virt_region: &MemoryRegion, ++ phys_region: &MemoryRegion, ++ attr: &AttributeFields, ++ ) -> Result<(), &'static str> { ++ assert!(self.initialized, "Translation tables not initialized"); ++ ++ if virt_region.size() != phys_region.size() { ++ return Err("Tried to map memory regions with unequal sizes"); ++ } ++ ++ if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() ++ { ++ return Err("Tried to map outside of physical address space"); ++ } ++ ++ let iter = phys_region.into_iter().zip(virt_region.into_iter()); ++ for (phys_page_addr, virt_page_addr) in iter { ++ let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); ++ let virt_page = virt_page_addr; ++ ++ self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; ++ } ++ ++ Ok(()) + } + } + +@@ -296,6 +379,9 @@ + //-------------------------------------------------------------------------------------------------- + + #[cfg(test)] ++pub type MinSizeTranslationTable = FixedSizeTranslationTable<1>; ++ ++#[cfg(test)] + mod tests { + use super::*; + use test_macros::kernel_test; + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs +@@ -15,7 +15,7 @@ + + use crate::{ + bsp, memory, +- memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, ++ memory::{mmu::TranslationGranule, Address, Physical}, + }; + use aarch64_cpu::{asm::barrier, registers::*}; + use core::intrinsics::unlikely; +@@ -46,13 +46,6 @@ + // Global instances + //-------------------------------------------------------------------------------------------------- + +-/// The kernel translation tables. +-/// +-/// # Safety +-/// +-/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". +-static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); +- + static MMU: MemoryManagementUnit = MemoryManagementUnit; + + //-------------------------------------------------------------------------------------------------- +@@ -87,7 +80,7 @@ + + /// Configure various settings of stage 1 of the EL1 translation regime. + fn configure_translation_control(&self) { +- let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; ++ let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI0::Used +@@ -119,7 +112,10 @@ + use memory::mmu::MMUEnableError; + + impl memory::mmu::interface::MMU for MemoryManagementUnit { +- unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { ++ unsafe fn enable_mmu_and_caching( ++ &self, ++ phys_tables_base_addr: Address, ++ ) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } +@@ -134,13 +130,8 @@ + // Prepare the memory attribute indirection register. + self.set_up_mair(); + +- // Populate translation tables. +- KERNEL_TABLES +- .populate_tt_entries() +- .map_err(MMUEnableError::Other)?; +- + // Set the "Translation Table Base Register". +- TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); ++ TTBR0_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + +@@ -163,33 +154,3 @@ + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } + } +- +-//-------------------------------------------------------------------------------------------------- +-// Testing +-//-------------------------------------------------------------------------------------------------- +- +-#[cfg(test)] +-mod tests { +- use super::*; +- use core::{cell::UnsafeCell, ops::Range}; +- use test_macros::kernel_test; +- +- /// Check if KERNEL_TABLES is in .bss. +- #[kernel_test] +- fn kernel_tables_in_bss() { +- extern "Rust" { +- static __bss_start: UnsafeCell; +- static __bss_end_exclusive: UnsafeCell; +- } +- +- let bss_range = unsafe { +- Range { +- start: __bss_start.get(), +- end: __bss_end_exclusive.get(), +- } +- }; +- let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; +- +- assert!(bss_range.contains(&kernel_tables_addr)); +- } +-} + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs +@@ -4,7 +4,11 @@ + + //! GICC Driver - GIC CPU interface. + +-use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; ++use crate::{ ++ bsp::device_driver::common::MMIODerefWrapper, ++ exception, ++ memory::{Address, Virtual}, ++}; + use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, +@@ -73,7 +77,7 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs +@@ -8,7 +8,9 @@ + //! - SPI - Shared Peripheral Interrupt. + + use crate::{ +- bsp::device_driver::common::MMIODerefWrapper, state, synchronization, ++ bsp::device_driver::common::MMIODerefWrapper, ++ memory::{Address, Virtual}, ++ state, synchronization, + synchronization::IRQSafeNullLock, + }; + use tock_registers::{ +@@ -128,7 +130,7 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs +@@ -81,7 +81,9 @@ + + use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, +- cpu, driver, exception, synchronization, ++ cpu, driver, exception, ++ memory::{Address, Virtual}, ++ synchronization, + synchronization::InitStateLock, + }; + +@@ -125,7 +127,10 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new( ++ gicd_mmio_start_addr: Address, ++ gicc_mmio_start_addr: Address, ++ ) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +@@ -5,8 +5,12 @@ + //! GPIO Driver. + + use crate::{ +- bsp::device_driver::common::MMIODerefWrapper, driver, exception::asynchronous::IRQNumber, +- synchronization, synchronization::IRQSafeNullLock, ++ bsp::device_driver::common::MMIODerefWrapper, ++ driver, ++ exception::asynchronous::IRQNumber, ++ memory::{Address, Virtual}, ++ synchronization, ++ synchronization::IRQSafeNullLock, + }; + use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, +@@ -131,7 +135,7 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } +@@ -198,7 +202,7 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +@@ -11,7 +11,9 @@ + use super::{PendingIRQs, PeripheralIRQ}; + use crate::{ + bsp::device_driver::common::MMIODerefWrapper, +- exception, synchronization, ++ exception, ++ memory::{Address, Virtual}, ++ synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, + }; + use tock_registers::{ +@@ -79,7 +81,7 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +@@ -10,6 +10,7 @@ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, ++ memory::{Address, Virtual}, + }; + use core::fmt; + +@@ -91,7 +92,7 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(periph_mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +@@ -13,6 +13,7 @@ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, ++ memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, + }; +@@ -244,7 +245,7 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, +@@ -395,7 +396,7 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/common.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/common.rs +@@ -4,6 +4,7 @@ + + //! Common device driver code. + ++use crate::memory::{Address, Virtual}; + use core::{fmt, marker::PhantomData, ops}; + + //-------------------------------------------------------------------------------------------------- +@@ -11,7 +12,7 @@ + //-------------------------------------------------------------------------------------------------- + + pub struct MMIODerefWrapper { +- start_addr: usize, ++ start_addr: Address, + phantom: PhantomData T>, + } + +@@ -25,7 +26,7 @@ + + impl MMIODerefWrapper { + /// Create an instance. +- pub const unsafe fn new(start_addr: usize) -> Self { ++ pub const unsafe fn new(start_addr: Address) -> Self { + Self { + start_addr, + phantom: PhantomData, +@@ -37,7 +38,7 @@ + type Target = T; + + fn deref(&self) -> &Self::Target { +- unsafe { &*(self.start_addr as *const _) } ++ unsafe { &*(self.start_addr.as_usize() as *const _) } + } + } + + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/driver.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/driver.rs +@@ -9,52 +9,109 @@ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, ++ memory, ++ memory::mmu::MMIODescriptor, ++}; ++use core::{ ++ mem::MaybeUninit, ++ sync::atomic::{AtomicBool, Ordering}, + }; +-use core::sync::atomic::{AtomicBool, Ordering}; + + //-------------------------------------------------------------------------------------------------- + // Global instances + //-------------------------------------------------------------------------------------------------- + +-static PL011_UART: device_driver::PL011Uart = +- unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +-static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; ++static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); ++static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + + #[cfg(feature = "bsp_rpi3")] +-static INTERRUPT_CONTROLLER: device_driver::InterruptController = +- unsafe { device_driver::InterruptController::new(mmio::PERIPHERAL_IC_START) }; ++static mut INTERRUPT_CONTROLLER: MaybeUninit = ++ MaybeUninit::uninit(); + + #[cfg(feature = "bsp_rpi4")] +-static INTERRUPT_CONTROLLER: device_driver::GICv2 = +- unsafe { device_driver::GICv2::new(mmio::GICD_START, mmio::GICC_START) }; ++static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); + + //-------------------------------------------------------------------------------------------------- + // Private Code + //-------------------------------------------------------------------------------------------------- + ++/// This must be called only after successful init of the memory subsystem. ++unsafe fn instantiate_uart() -> Result<(), &'static str> { ++ let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); ++ let virt_addr = ++ memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; ++ ++ PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); ++ ++ Ok(()) ++} ++ + /// This must be called only after successful init of the UART driver. +-fn post_init_uart() -> Result<(), &'static str> { +- console::register_console(&PL011_UART); ++unsafe fn post_init_uart() -> Result<(), &'static str> { ++ console::register_console(PL011_UART.assume_init_ref()); ++ ++ Ok(()) ++} ++ ++/// This must be called only after successful init of the memory subsystem. ++unsafe fn instantiate_gpio() -> Result<(), &'static str> { ++ let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); ++ let virt_addr = ++ memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; ++ ++ GPIO.write(device_driver::GPIO::new(virt_addr)); + + Ok(()) + } + + /// This must be called only after successful init of the GPIO driver. +-fn post_init_gpio() -> Result<(), &'static str> { +- GPIO.map_pl011_uart(); ++unsafe fn post_init_gpio() -> Result<(), &'static str> { ++ GPIO.assume_init_ref().map_pl011_uart(); ++ Ok(()) ++} ++ ++/// This must be called only after successful init of the memory subsystem. ++#[cfg(feature = "bsp_rpi3")] ++unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { ++ let periph_mmio_descriptor = ++ MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); ++ let periph_virt_addr = memory::mmu::kernel_map_mmio( ++ device_driver::InterruptController::COMPATIBLE, ++ &periph_mmio_descriptor, ++ )?; ++ ++ INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); ++ ++ Ok(()) ++} ++ ++/// This must be called only after successful init of the memory subsystem. ++#[cfg(feature = "bsp_rpi4")] ++unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { ++ let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); ++ let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; ++ ++ let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); ++ let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; ++ ++ INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); ++ + Ok(()) + } + + /// This must be called only after successful init of the interrupt controller driver. +-fn post_init_interrupt_controller() -> Result<(), &'static str> { +- generic_exception::asynchronous::register_irq_manager(&INTERRUPT_CONTROLLER); ++unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { ++ generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); + + Ok(()) + } + +-fn driver_uart() -> Result<(), &'static str> { ++/// Function needs to ensure that driver registration happens only after correct instantiation. ++unsafe fn driver_uart() -> Result<(), &'static str> { ++ instantiate_uart()?; ++ + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( +- &PL011_UART, ++ PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); +@@ -63,17 +120,26 @@ + Ok(()) + } + +-fn driver_gpio() -> Result<(), &'static str> { +- let gpio_descriptor = +- generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio), None); ++/// Function needs to ensure that driver registration happens only after correct instantiation. ++unsafe fn driver_gpio() -> Result<(), &'static str> { ++ instantiate_gpio()?; ++ ++ let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( ++ GPIO.assume_init_ref(), ++ Some(post_init_gpio), ++ None, ++ ); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) + } + +-fn driver_interrupt_controller() -> Result<(), &'static str> { ++/// Function needs to ensure that driver registration happens only after correct instantiation. ++unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { ++ instantiate_interrupt_controller()?; ++ + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( +- &INTERRUPT_CONTROLLER, ++ INTERRUPT_CONTROLLER.assume_init_ref(), + Some(post_init_interrupt_controller), + None, + ); +@@ -109,5 +175,10 @@ + /// than on real hardware due to QEMU's abstractions. + #[cfg(feature = "test_build")] + pub fn qemu_bring_up_console() { +- console::register_console(&PL011_UART); ++ use crate::cpu; ++ ++ unsafe { ++ instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); ++ console::register_console(PL011_UART.assume_init_ref()); ++ }; + } + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld +@@ -38,7 +38,7 @@ + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { +- /* ^ */ ++ __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ +@@ -67,6 +67,7 @@ + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ ++ __data_start = .; + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ +@@ -78,6 +79,18 @@ + __bss_end_exclusive = .; + } :segment_data + ++ . = ALIGN(PAGE_SIZE); ++ __data_end_exclusive = .; ++ ++ /*********************************************************************************************** ++ * MMIO Remap Reserved ++ ***********************************************************************************************/ ++ __mmio_remap_start = .; ++ . += 8 * 1024 * 1024; ++ __mmio_remap_end_exclusive = .; ++ ++ ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") ++ + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs +@@ -4,70 +4,163 @@ + + //! BSP Memory Management Unit. + +-use super::map as memory_map; +-use crate::memory::mmu::*; +-use core::ops::RangeInclusive; ++use crate::{ ++ memory::{ ++ mmu::{ ++ self as generic_mmu, AccessPermissions, AddressSpace, AssociatedTranslationTable, ++ AttributeFields, MemAttributes, MemoryRegion, PageAddress, TranslationGranule, ++ }, ++ Physical, Virtual, ++ }, ++ synchronization::InitStateLock, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++type KernelTranslationTable = ++ ::TableStartFromBottom; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions + //-------------------------------------------------------------------------------------------------- + +-/// The kernel's address space defined by this BSP. +-pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; ++/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to ++/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. ++pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; ++ ++/// The kernel's virtual address space defined by this BSP. ++pub type KernelVirtAddrSpace = AddressSpace<{ 1024 * 1024 * 1024 }>; + +-const NUM_MEM_RANGES: usize = 2; ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- + +-/// The virtual memory layout. ++/// The kernel translation tables. + /// +-/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. +-/// It is agnostic of the paging granularity that the architecture's MMU will use. +-pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( +- memory_map::END_INCLUSIVE, +- [ +- TranslationDescriptor { +- name: "Kernel code and RO data", +- virtual_range: code_range_inclusive, +- physical_range_translation: Translation::Identity, +- attribute_fields: AttributeFields { +- mem_attributes: MemAttributes::CacheableDRAM, +- acc_perms: AccessPermissions::ReadOnly, +- execute_never: false, +- }, +- }, +- TranslationDescriptor { +- name: "Device MMIO", +- virtual_range: mmio_range_inclusive, +- physical_range_translation: Translation::Identity, +- attribute_fields: AttributeFields { +- mem_attributes: MemAttributes::Device, +- acc_perms: AccessPermissions::ReadWrite, +- execute_never: true, +- }, +- }, +- ], +-); ++/// It is mandatory that InitStateLock is transparent. ++/// ++/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. ++/// There is a unit tests that checks this porperty. ++static KERNEL_TABLES: InitStateLock = ++ InitStateLock::new(KernelTranslationTable::new()); + + //-------------------------------------------------------------------------------------------------- + // Private Code + //-------------------------------------------------------------------------------------------------- + +-fn code_range_inclusive() -> RangeInclusive { +- // Notice the subtraction to turn the exclusive end into an inclusive end. +- #[allow(clippy::range_minus_one)] +- RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) ++/// Helper function for calculating the number of pages the given parameter spans. ++const fn size_to_num_pages(size: usize) -> usize { ++ assert!(size > 0); ++ assert!(size modulo KernelGranule::SIZE == 0); ++ ++ size >> KernelGranule::SHIFT ++} ++ ++/// The code pages of the kernel binary. ++fn virt_code_region() -> MemoryRegion { ++ let num_pages = size_to_num_pages(super::code_size()); ++ ++ let start_page_addr = super::virt_code_start(); ++ let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); ++ ++ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) ++} ++ ++/// The data pages of the kernel binary. ++fn virt_data_region() -> MemoryRegion { ++ let num_pages = size_to_num_pages(super::data_size()); ++ ++ let start_page_addr = super::virt_data_start(); ++ let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); ++ ++ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) ++} ++ ++/// The boot core stack pages. ++fn virt_boot_core_stack_region() -> MemoryRegion { ++ let num_pages = size_to_num_pages(super::boot_core_stack_size()); ++ ++ let start_page_addr = super::virt_boot_core_stack_start(); ++ let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); ++ ++ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) + } + +-fn mmio_range_inclusive() -> RangeInclusive { +- RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) ++// The binary is still identity mapped, so use this trivial conversion function for mapping below. ++ ++fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { ++ MemoryRegion::new( ++ PageAddress::from(virt_region.start_page_addr().into_inner().as_usize()), ++ PageAddress::from( ++ virt_region ++ .end_exclusive_page_addr() ++ .into_inner() ++ .as_usize(), ++ ), ++ ) + } + + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- + +-/// Return a reference to the virtual memory layout. +-pub fn virt_mem_layout() -> &'static KernelVirtualLayout { +- &LAYOUT ++/// Return a reference to the kernel's translation tables. ++pub fn kernel_translation_tables() -> &'static InitStateLock { ++ &KERNEL_TABLES ++} ++ ++/// The MMIO remap pages. ++pub fn virt_mmio_remap_region() -> MemoryRegion { ++ let num_pages = size_to_num_pages(super::mmio_remap_size()); ++ ++ let start_page_addr = super::virt_mmio_remap_start(); ++ let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); ++ ++ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) ++} ++ ++/// Map the kernel binary. ++/// ++/// # Safety ++/// ++/// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking. ++pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { ++ generic_mmu::kernel_map_at( ++ "Kernel boot-core stack", ++ &virt_boot_core_stack_region(), ++ &kernel_virt_to_phys_region(virt_boot_core_stack_region()), ++ &AttributeFields { ++ mem_attributes: MemAttributes::CacheableDRAM, ++ acc_perms: AccessPermissions::ReadWrite, ++ execute_never: true, ++ }, ++ )?; ++ ++ generic_mmu::kernel_map_at( ++ "Kernel code and RO data", ++ &virt_code_region(), ++ &kernel_virt_to_phys_region(virt_code_region()), ++ &AttributeFields { ++ mem_attributes: MemAttributes::CacheableDRAM, ++ acc_perms: AccessPermissions::ReadOnly, ++ execute_never: false, ++ }, ++ )?; ++ ++ generic_mmu::kernel_map_at( ++ "Kernel data and bss", ++ &virt_data_region(), ++ &kernel_virt_to_phys_region(virt_data_region()), ++ &AttributeFields { ++ mem_attributes: MemAttributes::CacheableDRAM, ++ acc_perms: AccessPermissions::ReadWrite, ++ execute_never: true, ++ }, ++ )?; ++ ++ Ok(()) + } + + //-------------------------------------------------------------------------------------------------- +@@ -77,38 +170,60 @@ + #[cfg(test)] + mod tests { + use super::*; ++ use core::{cell::UnsafeCell, ops::Range}; + use test_macros::kernel_test; + + /// Check alignment of the kernel's virtual memory layout sections. + #[kernel_test] + fn virt_mem_layout_sections_are_64KiB_aligned() { +- const SIXTYFOUR_KIB: usize = 65536; +- +- for i in LAYOUT.inner().iter() { +- let start: usize = *(i.virtual_range)().start(); +- let end: usize = *(i.virtual_range)().end() + 1; +- +- assert_eq!(start modulo SIXTYFOUR_KIB, 0); +- assert_eq!(end modulo SIXTYFOUR_KIB, 0); +- assert!(end >= start); ++ for i in [ ++ virt_boot_core_stack_region, ++ virt_code_region, ++ virt_data_region, ++ ] ++ .iter() ++ { ++ let start = i().start_page_addr().into_inner(); ++ let end_exclusive = i().end_exclusive_page_addr().into_inner(); ++ ++ assert!(start.is_page_aligned()); ++ assert!(end_exclusive.is_page_aligned()); ++ assert!(end_exclusive >= start); + } + } + + /// Ensure the kernel's virtual memory layout is free of overlaps. + #[kernel_test] + fn virt_mem_layout_has_no_overlaps() { +- let layout = virt_mem_layout().inner(); +- +- for (i, first) in layout.iter().enumerate() { +- for second in layout.iter().skip(i + 1) { +- let first_range = first.virtual_range; +- let second_range = second.virtual_range; +- +- assert!(!first_range().contains(second_range().start())); +- assert!(!first_range().contains(second_range().end())); +- assert!(!second_range().contains(first_range().start())); +- assert!(!second_range().contains(first_range().end())); ++ let layout = [ ++ virt_boot_core_stack_region(), ++ virt_code_region(), ++ virt_data_region(), ++ ]; ++ ++ for (i, first_range) in layout.iter().enumerate() { ++ for second_range in layout.iter().skip(i + 1) { ++ assert!(!first_range.overlaps(second_range)) + } + } + } ++ ++ /// Check if KERNEL_TABLES is in .bss. ++ #[kernel_test] ++ fn kernel_tables_in_bss() { ++ extern "Rust" { ++ static __bss_start: UnsafeCell; ++ static __bss_end_exclusive: UnsafeCell; ++ } ++ ++ let bss_range = unsafe { ++ Range { ++ start: __bss_start.get(), ++ end: __bss_end_exclusive.get(), ++ } ++ }; ++ let kernel_tables_addr = &KERNEL_TABLES as *const _ as usize as *mut u64; ++ ++ assert!(bss_range.contains(&kernel_tables_addr)); ++ } + } + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs +@@ -10,27 +10,59 @@ + //! as the boot core's stack. + //! + //! +---------------------------------------+ +-//! | | 0x0 ++//! | | boot_core_stack_start @ 0x0 + //! | | ^ + //! | Boot-core Stack | | stack + //! | | | growth + //! | | | direction + //! +---------------------------------------+ +-//! | | code_start @ 0x8_0000 ++//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive + //! | .text | + //! | .rodata | + //! | .got | + //! | | + //! +---------------------------------------+ +-//! | | code_end_exclusive ++//! | | data_start == code_end_exclusive + //! | .data | + //! | .bss | + //! | | + //! +---------------------------------------+ ++//! | | data_end_exclusive + //! | | ++//! ++//! ++//! ++//! ++//! ++//! The virtual memory layout is as follows: ++//! ++//! +---------------------------------------+ ++//! | | boot_core_stack_start @ 0x0 ++//! | | ^ ++//! | Boot-core Stack | | stack ++//! | | | growth ++//! | | | direction ++//! +---------------------------------------+ ++//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive ++//! | .text | ++//! | .rodata | ++//! | .got | ++//! | | ++//! +---------------------------------------+ ++//! | | data_start == code_end_exclusive ++//! | .data | ++//! | .bss | ++//! | | ++//! +---------------------------------------+ ++//! | | mmio_remap_start == data_end_exclusive ++//! | VA region for MMIO remapping | ++//! | | ++//! +---------------------------------------+ ++//! | | mmio_remap_end_exclusive + //! | | + pub mod mmu; + ++use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; + use core::cell::UnsafeCell; + + //-------------------------------------------------------------------------------------------------- +@@ -41,6 +73,15 @@ + extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; ++ ++ static __data_start: UnsafeCell<()>; ++ static __data_end_exclusive: UnsafeCell<()>; ++ ++ static __mmio_remap_start: UnsafeCell<()>; ++ static __mmio_remap_end_exclusive: UnsafeCell<()>; ++ ++ static __boot_core_stack_start: UnsafeCell<()>; ++ static __boot_core_stack_end_exclusive: UnsafeCell<()>; + } + + //-------------------------------------------------------------------------------------------------- +@@ -50,34 +91,23 @@ + /// The board's physical memory map. + #[rustfmt::skip] + pub(super) mod map { +- /// The inclusive end address of the memory map. +- /// +- /// End address + 1 must be power of two. +- /// +- /// # Note +- /// +- /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for +- /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. +- /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. +- /// +- /// However, making this trade-off has the downside of making it possible for the CPU to assert a +- /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on +- /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. +- pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; +- +- pub const GPIO_OFFSET: usize = 0x0020_0000; +- pub const UART_OFFSET: usize = 0x0020_1000; ++ use super::*; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + +- pub const START: usize = 0x3F00_0000; +- pub const PERIPHERAL_IC_START: usize = START + 0x0000_B200; +- pub const GPIO_START: usize = START + GPIO_OFFSET; +- pub const PL011_UART_START: usize = START + UART_OFFSET; +- pub const END_INCLUSIVE: usize = 0x4000_FFFF; ++ pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); ++ pub const PERIPHERAL_IC_SIZE: usize = 0x24; ++ ++ pub const GPIO_START: Address = Address::new(0x3F20_0000); ++ pub const GPIO_SIZE: usize = 0xA0; ++ ++ pub const PL011_UART_START: Address = Address::new(0x3F20_1000); ++ pub const PL011_UART_SIZE: usize = 0x48; ++ ++ pub const END: Address = Address::new(0x4001_0000); + } + + /// Physical devices. +@@ -85,13 +115,22 @@ + pub mod mmio { + use super::*; + +- pub const START: usize = 0xFE00_0000; +- pub const GPIO_START: usize = START + GPIO_OFFSET; +- pub const PL011_UART_START: usize = START + UART_OFFSET; +- pub const GICD_START: usize = 0xFF84_1000; +- pub const GICC_START: usize = 0xFF84_2000; +- pub const END_INCLUSIVE: usize = 0xFF84_FFFF; ++ pub const GPIO_START: Address = Address::new(0xFE20_0000); ++ pub const GPIO_SIZE: usize = 0xA0; ++ ++ pub const PL011_UART_START: Address = Address::new(0xFE20_1000); ++ pub const PL011_UART_SIZE: usize = 0x48; ++ ++ pub const GICD_START: Address = Address::new(0xFF84_1000); ++ pub const GICD_SIZE: usize = 0x824; ++ ++ pub const GICC_START: Address = Address::new(0xFF84_2000); ++ pub const GICC_SIZE: usize = 0x14; ++ ++ pub const END: Address = Address::new(0xFF85_0000); + } ++ ++ pub const END: Address = mmio::END; + } + + //-------------------------------------------------------------------------------------------------- +@@ -104,15 +143,76 @@ + /// + /// - Value is provided by the linker script and must be trusted as-is. + #[inline(always)] +-fn code_start() -> usize { +- unsafe { __code_start.get() as usize } ++fn virt_code_start() -> PageAddress { ++ PageAddress::from(unsafe { __code_start.get() as usize }) + } + +-/// Exclusive end page address of the code segment. ++/// Size of the code segment. ++/// + /// # Safety + /// + /// - Value is provided by the linker script and must be trusted as-is. + #[inline(always)] +-fn code_end_exclusive() -> usize { +- unsafe { __code_end_exclusive.get() as usize } ++fn code_size() -> usize { ++ unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } ++} ++ ++/// Start page address of the data segment. ++#[inline(always)] ++fn virt_data_start() -> PageAddress { ++ PageAddress::from(unsafe { __data_start.get() as usize }) ++} ++ ++/// Size of the data segment. ++/// ++/// # Safety ++/// ++/// - Value is provided by the linker script and must be trusted as-is. ++#[inline(always)] ++fn data_size() -> usize { ++ unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } ++} ++ ++/// Start page address of the MMIO remap reservation. ++/// ++/// # Safety ++/// ++/// - Value is provided by the linker script and must be trusted as-is. ++#[inline(always)] ++fn virt_mmio_remap_start() -> PageAddress { ++ PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) ++} ++ ++/// Size of the MMIO remap reservation. ++/// ++/// # Safety ++/// ++/// - Value is provided by the linker script and must be trusted as-is. ++#[inline(always)] ++fn mmio_remap_size() -> usize { ++ unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } ++} ++ ++/// Start page address of the boot core's stack. ++#[inline(always)] ++fn virt_boot_core_stack_start() -> PageAddress { ++ PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) ++} ++ ++/// Size of the boot core's stack. ++#[inline(always)] ++fn boot_core_stack_size() -> usize { ++ unsafe { ++ (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Exclusive end address of the physical address space. ++#[inline(always)] ++pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { ++ PageAddress::from(map::END) + } + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/common.rs 14_virtual_mem_part2_mmio_remap/kernel/src/common.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/common.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/common.rs +@@ -4,6 +4,30 @@ + + //! General purpose code. + ++/// Check if a value is aligned to a given size. ++#[inline(always)] ++pub const fn is_aligned(value: usize, alignment: usize) -> bool { ++ assert!(alignment.is_power_of_two()); ++ ++ (value & (alignment - 1)) == 0 ++} ++ ++/// Align down. ++#[inline(always)] ++pub const fn align_down(value: usize, alignment: usize) -> usize { ++ assert!(alignment.is_power_of_two()); ++ ++ value & !(alignment - 1) ++} ++ ++/// Align up. ++#[inline(always)] ++pub const fn align_up(value: usize, alignment: usize) -> usize { ++ assert!(alignment.is_power_of_two()); ++ ++ (value + alignment - 1) & !(alignment - 1) ++} ++ + /// Convert a size into human readable format. + pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs +@@ -114,10 +114,13 @@ + #![feature(const_option)] + #![feature(core_intrinsics)] + #![feature(format_args_nl)] ++#![feature(generic_const_exprs)] + #![feature(int_roundings)] ++#![feature(is_sorted)] + #![feature(linkage)] + #![feature(nonzero_min_max)] + #![feature(panic_info_message)] ++#![feature(step_trait)] + #![feature(trait_alias)] + #![feature(unchecked_math)] + #![no_std] +@@ -184,6 +187,17 @@ + #[no_mangle] + unsafe fn kernel_init() -> ! { + exception::handling_init(); ++ ++ let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { ++ Err(string) => panic!("Error mapping kernel binary: {}", string), ++ Ok(addr) => addr, ++ }; ++ ++ if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { ++ panic!("Enabling MMU failed: {}", e); ++ } ++ ++ memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs +@@ -26,14 +26,19 @@ + /// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. + #[no_mangle] + unsafe fn kernel_init() -> ! { +- use memory::mmu::interface::MMU; +- + exception::handling_init(); + +- if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { +- panic!("MMU: {}", string); ++ let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { ++ Err(string) => panic!("Error mapping kernel binary: {}", string), ++ Ok(addr) => addr, ++ }; ++ ++ if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { ++ panic!("Enabling MMU failed: {}", e); + } + ++ memory::mmu::post_enable_init(); ++ + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); +@@ -57,8 +62,8 @@ + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + +- info!("MMU online. Special regions:"); +- bsp::memory::mmu::virt_mem_layout().print_layout(); ++ info!("MMU online:"); ++ memory::mmu::kernel_print_mappings(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/mapping_record.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/mapping_record.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs +@@ -0,0 +1,238 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! A record of mapped pages. ++ ++use super::{ ++ AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, ++ Physical, Virtual, ++}; ++use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Type describing a virtual memory mapping. ++#[allow(missing_docs)] ++#[derive(Copy, Clone)] ++struct MappingRecordEntry { ++ pub users: [Option<&'static str>; 5], ++ pub phys_start_addr: Address, ++ pub virt_start_addr: Address, ++ pub num_pages: usize, ++ pub attribute_fields: AttributeFields, ++} ++ ++struct MappingRecord { ++ inner: [Option; 12], ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static KERNEL_MAPPING_RECORD: InitStateLock = ++ InitStateLock::new(MappingRecord::new()); ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl MappingRecordEntry { ++ pub fn new( ++ name: &'static str, ++ virt_region: &MemoryRegion, ++ phys_region: &MemoryRegion, ++ attr: &AttributeFields, ++ ) -> Self { ++ Self { ++ users: [Some(name), None, None, None, None], ++ phys_start_addr: phys_region.start_addr(), ++ virt_start_addr: virt_region.start_addr(), ++ num_pages: phys_region.num_pages(), ++ attribute_fields: *attr, ++ } ++ } ++ ++ fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { ++ if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { ++ return Ok(x); ++ }; ++ ++ Err("Storage for user info exhausted") ++ } ++ ++ pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { ++ let x = self.find_next_free_user()?; ++ *x = Some(user); ++ Ok(()) ++ } ++} ++ ++impl MappingRecord { ++ pub const fn new() -> Self { ++ Self { inner: [None; 12] } ++ } ++ ++ fn size(&self) -> usize { ++ self.inner.iter().filter(|x| x.is_some()).count() ++ } ++ ++ fn sort(&mut self) { ++ let upper_bound_exclusive = self.size(); ++ let entries = &mut self.inner[0..upper_bound_exclusive]; ++ ++ if !entries.is_sorted_by_key(|item| item.unwrap().virt_start_addr) { ++ entries.sort_unstable_by_key(|item| item.unwrap().virt_start_addr) ++ } ++ } ++ ++ fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { ++ if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { ++ return Ok(x); ++ } ++ ++ Err("Storage for mapping info exhausted") ++ } ++ ++ fn find_duplicate( ++ &mut self, ++ phys_region: &MemoryRegion, ++ ) -> Option<&mut MappingRecordEntry> { ++ self.inner ++ .iter_mut() ++ .filter_map(|x| x.as_mut()) ++ .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) ++ .find(|x| { ++ if x.phys_start_addr != phys_region.start_addr() { ++ return false; ++ } ++ ++ if x.num_pages != phys_region.num_pages() { ++ return false; ++ } ++ ++ true ++ }) ++ } ++ ++ pub fn add( ++ &mut self, ++ name: &'static str, ++ virt_region: &MemoryRegion, ++ phys_region: &MemoryRegion, ++ attr: &AttributeFields, ++ ) -> Result<(), &'static str> { ++ let x = self.find_next_free()?; ++ ++ *x = Some(MappingRecordEntry::new( ++ name, ++ virt_region, ++ phys_region, ++ attr, ++ )); ++ ++ self.sort(); ++ ++ Ok(()) ++ } ++ ++ pub fn print(&self) { ++ info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); ++ info!( ++ " {:^44} {:^30} {:^7} {:^9} {:^35}", ++ "Virtual", "Physical", "Size", "Attr", "Entity" ++ ); ++ info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); ++ ++ for i in self.inner.iter().flatten() { ++ let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; ++ let virt_start = i.virt_start_addr; ++ let virt_end_inclusive = virt_start + (size - 1); ++ let phys_start = i.phys_start_addr; ++ let phys_end_inclusive = phys_start + (size - 1); ++ ++ let (size, unit) = common::size_human_readable_ceil(size); ++ ++ let attr = match i.attribute_fields.mem_attributes { ++ MemAttributes::CacheableDRAM => "C", ++ MemAttributes::Device => "Dev", ++ }; ++ ++ let acc_p = match i.attribute_fields.acc_perms { ++ AccessPermissions::ReadOnly => "RO", ++ AccessPermissions::ReadWrite => "RW", ++ }; ++ ++ let xn = if i.attribute_fields.execute_never { ++ "XN" ++ } else { ++ "X" ++ }; ++ ++ info!( ++ " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", ++ virt_start, ++ virt_end_inclusive, ++ phys_start, ++ phys_end_inclusive, ++ size, ++ unit, ++ attr, ++ acc_p, ++ xn, ++ i.users[0].unwrap() ++ ); ++ ++ for k in i.users[1..].iter() { ++ if let Some(additional_user) = *k { ++ info!( ++ " | {}", ++ additional_user ++ ); ++ } ++ } ++ } ++ ++ info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++use synchronization::interface::ReadWriteEx; ++ ++/// Add an entry to the mapping info record. ++pub fn kernel_add( ++ name: &'static str, ++ virt_region: &MemoryRegion, ++ phys_region: &MemoryRegion, ++ attr: &AttributeFields, ++) -> Result<(), &'static str> { ++ KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) ++} ++ ++pub fn kernel_find_and_insert_mmio_duplicate( ++ mmio_descriptor: &MMIODescriptor, ++ new_user: &'static str, ++) -> Option> { ++ let phys_region: MemoryRegion = (*mmio_descriptor).into(); ++ ++ KERNEL_MAPPING_RECORD.write(|mr| { ++ let dup = mr.find_duplicate(&phys_region)?; ++ ++ if let Err(x) = dup.add_user(new_user) { ++ warn!("{}", x); ++ } ++ ++ Some(dup.virt_start_addr) ++ }) ++} ++ ++/// Human-readable print of all recorded kernel mappings. ++pub fn kernel_print() { ++ KERNEL_MAPPING_RECORD.read(|mr| mr.print()); ++} + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/page_alloc.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/page_alloc.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs +@@ -0,0 +1,70 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2021-2023 Andre Richter ++ ++//! Page allocation. ++ ++use super::MemoryRegion; ++use crate::{ ++ memory::{AddressType, Virtual}, ++ synchronization::IRQSafeNullLock, ++ warn, ++}; ++use core::num::NonZeroUsize; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// A page allocator that can be lazyily initialized. ++pub struct PageAllocator { ++ pool: Option>, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = ++ IRQSafeNullLock::new(PageAllocator::new()); ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Return a reference to the kernel's MMIO virtual address allocator. ++pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { ++ &KERNEL_MMIO_VA_ALLOCATOR ++} ++ ++impl PageAllocator { ++ /// Create an instance. ++ pub const fn new() -> Self { ++ Self { pool: None } ++ } ++ ++ /// Initialize the allocator. ++ pub fn init(&mut self, pool: MemoryRegion) { ++ if self.pool.is_some() { ++ warn!("Already initialized"); ++ return; ++ } ++ ++ self.pool = Some(pool); ++ } ++ ++ /// Allocate a number of pages. ++ pub fn alloc( ++ &mut self, ++ num_requested_pages: NonZeroUsize, ++ ) -> Result, &'static str> { ++ if self.pool.is_none() { ++ return Err("Allocator not initialized"); ++ } ++ ++ self.pool ++ .as_mut() ++ .unwrap() ++ .take_first_n_pages(num_requested_pages) ++ } ++} + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs +@@ -8,7 +8,91 @@ + #[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] + mod arch_translation_table; + ++use super::{AttributeFields, MemoryRegion}; ++use crate::memory::{Address, Physical, Virtual}; ++ + //-------------------------------------------------------------------------------------------------- + // Architectural Public Reexports + //-------------------------------------------------------------------------------------------------- +-pub use arch_translation_table::KernelTranslationTable; ++#[cfg(target_arch = "aarch64")] ++pub use arch_translation_table::FixedSizeTranslationTable; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Translation table interfaces. ++pub mod interface { ++ use super::*; ++ ++ /// Translation table operations. ++ pub trait TranslationTable { ++ /// Anything that needs to run before any of the other provided functions can be used. ++ /// ++ /// # Safety ++ /// ++ /// - Implementor must ensure that this function can run only once or is harmless if invoked ++ /// multiple times. ++ fn init(&mut self); ++ ++ /// The translation table's base address to be used for programming the MMU. ++ fn phys_base_address(&self) -> Address; ++ ++ /// Map the given virtual memory region to the given physical memory region. ++ /// ++ /// # Safety ++ /// ++ /// - Using wrong attributes can cause multiple issues of different nature in the system. ++ /// - It is not required that the architectural implementation prevents aliasing. That is, ++ /// mapping to the same physical memory using multiple virtual addresses, which would ++ /// break Rust's ownership assumptions. This should be protected against in the kernel's ++ /// generic MMU code. ++ unsafe fn map_at( ++ &mut self, ++ virt_region: &MemoryRegion, ++ phys_region: &MemoryRegion, ++ attr: &AttributeFields, ++ ) -> Result<(), &'static str>; ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Testing ++//-------------------------------------------------------------------------------------------------- ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; ++ use arch_translation_table::MinSizeTranslationTable; ++ use interface::TranslationTable; ++ use test_macros::kernel_test; ++ ++ /// Sanity checks for the TranslationTable implementation. ++ #[kernel_test] ++ fn translationtable_implementation_sanity() { ++ // This will occupy a lot of space on the stack. ++ let mut tables = MinSizeTranslationTable::new(); ++ ++ tables.init(); ++ ++ let virt_start_page_addr: PageAddress = PageAddress::from(0); ++ let virt_end_exclusive_page_addr: PageAddress = ++ virt_start_page_addr.checked_offset(5).unwrap(); ++ ++ let phys_start_page_addr: PageAddress = PageAddress::from(0); ++ let phys_end_exclusive_page_addr: PageAddress = ++ phys_start_page_addr.checked_offset(5).unwrap(); ++ ++ let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); ++ let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); ++ ++ let attr = AttributeFields { ++ mem_attributes: MemAttributes::CacheableDRAM, ++ acc_perms: AccessPermissions::ReadWrite, ++ execute_never: true, ++ }; ++ ++ unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; ++ } ++} + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/types.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/types.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs +@@ -0,0 +1,373 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2020-2023 Andre Richter ++ ++//! Memory Management Unit types. ++ ++use crate::{ ++ bsp, common, ++ memory::{Address, AddressType, Physical}, ++}; ++use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// A wrapper type around [Address] that ensures page alignment. ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] ++pub struct PageAddress { ++ inner: Address, ++} ++ ++/// A type that describes a region of memory in quantities of pages. ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] ++pub struct MemoryRegion { ++ start: PageAddress, ++ end_exclusive: PageAddress, ++} ++ ++/// Architecture agnostic memory attributes. ++#[allow(missing_docs)] ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] ++pub enum MemAttributes { ++ CacheableDRAM, ++ Device, ++} ++ ++/// Architecture agnostic access permissions. ++#[allow(missing_docs)] ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] ++pub enum AccessPermissions { ++ ReadOnly, ++ ReadWrite, ++} ++ ++/// Collection of memory attributes. ++#[allow(missing_docs)] ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] ++pub struct AttributeFields { ++ pub mem_attributes: MemAttributes, ++ pub acc_perms: AccessPermissions, ++ pub execute_never: bool, ++} ++ ++/// An MMIO descriptor for use in device drivers. ++#[derive(Copy, Clone)] ++pub struct MMIODescriptor { ++ start_addr: Address, ++ end_addr_exclusive: Address, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++//------------------------------------------------------------------------------ ++// PageAddress ++//------------------------------------------------------------------------------ ++impl PageAddress { ++ /// Unwraps the value. ++ pub fn into_inner(self) -> Address { ++ self.inner ++ } ++ ++ /// Calculates the offset from the page address. ++ /// ++ /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * ++ /// page_size`. ++ pub fn checked_offset(self, count: isize) -> Option { ++ if count == 0 { ++ return Some(self); ++ } ++ ++ let delta = count ++ .unsigned_abs() ++ .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; ++ let result = if count.is_positive() { ++ self.inner.as_usize().checked_add(delta)? ++ } else { ++ self.inner.as_usize().checked_sub(delta)? ++ }; ++ ++ Some(Self { ++ inner: Address::new(result), ++ }) ++ } ++} ++ ++impl From for PageAddress { ++ fn from(addr: usize) -> Self { ++ assert!( ++ common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), ++ "Input usize not page aligned" ++ ); ++ ++ Self { ++ inner: Address::new(addr), ++ } ++ } ++} ++ ++impl From> for PageAddress { ++ fn from(addr: Address) -> Self { ++ assert!(addr.is_page_aligned(), "Input Address not page aligned"); ++ ++ Self { inner: addr } ++ } ++} ++ ++impl Step for PageAddress { ++ fn steps_between(start: &Self, end: &Self) -> Option { ++ if start > end { ++ return None; ++ } ++ ++ // Since start <= end, do unchecked arithmetic. ++ Some( ++ (end.inner.as_usize() - start.inner.as_usize()) ++ >> bsp::memory::mmu::KernelGranule::SHIFT, ++ ) ++ } ++ ++ fn forward_checked(start: Self, count: usize) -> Option { ++ start.checked_offset(count as isize) ++ } ++ ++ fn backward_checked(start: Self, count: usize) -> Option { ++ start.checked_offset(-(count as isize)) ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// MemoryRegion ++//------------------------------------------------------------------------------ ++impl MemoryRegion { ++ /// Create an instance. ++ pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { ++ assert!(start <= end_exclusive); ++ ++ Self { ++ start, ++ end_exclusive, ++ } ++ } ++ ++ fn as_range(&self) -> Range> { ++ self.into_iter() ++ } ++ ++ /// Returns the start page address. ++ pub fn start_page_addr(&self) -> PageAddress { ++ self.start ++ } ++ ++ /// Returns the start address. ++ pub fn start_addr(&self) -> Address { ++ self.start.into_inner() ++ } ++ ++ /// Returns the exclusive end page address. ++ pub fn end_exclusive_page_addr(&self) -> PageAddress { ++ self.end_exclusive ++ } ++ ++ /// Returns the exclusive end page address. ++ pub fn end_inclusive_page_addr(&self) -> PageAddress { ++ self.end_exclusive.checked_offset(-1).unwrap() ++ } ++ ++ /// Checks if self contains an address. ++ pub fn contains(&self, addr: Address) -> bool { ++ let page_addr = PageAddress::from(addr.align_down_page()); ++ self.as_range().contains(&page_addr) ++ } ++ ++ /// Checks if there is an overlap with another memory region. ++ pub fn overlaps(&self, other_region: &Self) -> bool { ++ let self_range = self.as_range(); ++ ++ self_range.contains(&other_region.start_page_addr()) ++ || self_range.contains(&other_region.end_inclusive_page_addr()) ++ } ++ ++ /// Returns the number of pages contained in this region. ++ pub fn num_pages(&self) -> usize { ++ PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() ++ } ++ ++ /// Returns the size in bytes of this region. ++ pub fn size(&self) -> usize { ++ // Invariant: start <= end_exclusive, so do unchecked arithmetic. ++ let end_exclusive = self.end_exclusive.into_inner().as_usize(); ++ let start = self.start.into_inner().as_usize(); ++ ++ end_exclusive - start ++ } ++ ++ /// Splits the MemoryRegion like: ++ /// ++ /// -------------------------------------------------------------------------------- ++ /// | | | | | | | | | | | | | | | | | | | ++ /// -------------------------------------------------------------------------------- ++ /// ^ ^ ^ ++ /// | | | ++ /// left_start left_end_exclusive | ++ /// | ++ /// ^ | ++ /// | | ++ /// right_start right_end_exclusive ++ /// ++ /// Left region is returned to the caller. Right region is the new region for this struct. ++ pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { ++ let count: usize = num_pages.into(); ++ ++ let left_end_exclusive = self.start.checked_offset(count as isize); ++ let left_end_exclusive = match left_end_exclusive { ++ None => return Err("Overflow while calculating left_end_exclusive"), ++ Some(x) => x, ++ }; ++ ++ if left_end_exclusive > self.end_exclusive { ++ return Err("Not enough free pages"); ++ } ++ ++ let allocation = Self { ++ start: self.start, ++ end_exclusive: left_end_exclusive, ++ }; ++ self.start = left_end_exclusive; ++ ++ Ok(allocation) ++ } ++} ++ ++impl IntoIterator for MemoryRegion { ++ type Item = PageAddress; ++ type IntoIter = Range; ++ ++ fn into_iter(self) -> Self::IntoIter { ++ Range { ++ start: self.start, ++ end: self.end_exclusive, ++ } ++ } ++} ++ ++impl From for MemoryRegion { ++ fn from(desc: MMIODescriptor) -> Self { ++ let start = PageAddress::from(desc.start_addr.align_down_page()); ++ let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); ++ ++ Self { ++ start, ++ end_exclusive, ++ } ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// MMIODescriptor ++//------------------------------------------------------------------------------ ++ ++impl MMIODescriptor { ++ /// Create an instance. ++ pub const fn new(start_addr: Address, size: usize) -> Self { ++ assert!(size > 0); ++ let end_addr_exclusive = Address::new(start_addr.as_usize() + size); ++ ++ Self { ++ start_addr, ++ end_addr_exclusive, ++ } ++ } ++ ++ /// Return the start address. ++ pub const fn start_addr(&self) -> Address { ++ self.start_addr ++ } ++ ++ /// Return the exclusive end address. ++ pub fn end_addr_exclusive(&self) -> Address { ++ self.end_addr_exclusive ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Testing ++//-------------------------------------------------------------------------------------------------- ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ use crate::memory::Virtual; ++ use test_macros::kernel_test; ++ ++ /// Sanity of [PageAddress] methods. ++ #[kernel_test] ++ fn pageaddress_type_method_sanity() { ++ let page_addr: PageAddress = ++ PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); ++ ++ assert_eq!( ++ page_addr.checked_offset(-2), ++ Some(PageAddress::::from(0)) ++ ); ++ ++ assert_eq!( ++ page_addr.checked_offset(2), ++ Some(PageAddress::::from( ++ bsp::memory::mmu::KernelGranule::SIZE * 4 ++ )) ++ ); ++ ++ assert_eq!( ++ PageAddress::::from(0).checked_offset(0), ++ Some(PageAddress::::from(0)) ++ ); ++ assert_eq!(PageAddress::::from(0).checked_offset(-1), None); ++ ++ let max_page_addr = Address::::new(usize::MAX).align_down_page(); ++ assert_eq!( ++ PageAddress::::from(max_page_addr).checked_offset(1), ++ None ++ ); ++ ++ let zero = PageAddress::::from(0); ++ let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); ++ assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); ++ } ++ ++ /// Sanity of [MemoryRegion] methods. ++ #[kernel_test] ++ fn memoryregion_type_method_sanity() { ++ let zero = PageAddress::::from(0); ++ let zero_region = MemoryRegion::new(zero, zero); ++ assert_eq!(zero_region.num_pages(), 0); ++ assert_eq!(zero_region.size(), 0); ++ ++ let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); ++ let one_region = MemoryRegion::new(zero, one); ++ assert_eq!(one_region.num_pages(), 1); ++ assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); ++ ++ let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); ++ let mut three_region = MemoryRegion::new(zero, three); ++ assert!(three_region.contains(zero.into_inner())); ++ assert!(!three_region.contains(three.into_inner())); ++ assert!(three_region.overlaps(&one_region)); ++ ++ let allocation = three_region ++ .take_first_n_pages(NonZeroUsize::new(2).unwrap()) ++ .unwrap(); ++ assert_eq!(allocation.num_pages(), 2); ++ assert_eq!(three_region.num_pages(), 1); ++ ++ for (i, alloc) in allocation.into_iter().enumerate() { ++ assert_eq!( ++ alloc.into_inner().as_usize(), ++ i * bsp::memory::mmu::KernelGranule::SIZE ++ ); ++ } ++ } ++} + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs +@@ -3,30 +3,24 @@ + // Copyright (c) 2020-2023 Andre Richter + + //! Memory Management Unit. +-//! +-//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file +-//! provides types for composing an architecture-agnostic description of the kernel's virtual memory +-//! layout. +-//! +-//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` +-//! function. +-//! +-//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and +-//! install respective translation tables. + + #[cfg(target_arch = "aarch64")] + #[path = "../_arch/aarch64/memory/mmu.rs"] + mod arch_mmu; + ++mod mapping_record; ++mod page_alloc; + mod translation_table; ++mod types; + +-use crate::common; +-use core::{fmt, ops::RangeInclusive}; ++use crate::{ ++ bsp, ++ memory::{Address, Physical, Virtual}, ++ synchronization, warn, ++}; ++use core::{fmt, num::NonZeroUsize}; + +-//-------------------------------------------------------------------------------------------------- +-// Architectural Public Reexports +-//-------------------------------------------------------------------------------------------------- +-pub use arch_mmu::mmu; ++pub use types::*; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions +@@ -46,13 +40,15 @@ + + /// MMU functions. + pub trait MMU { +- /// Called by the kernel during early init. Supposed to take the translation tables from the +- /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. ++ /// Turns on the MMU for the first time and enables data and instruction caching. + /// + /// # Safety + /// + /// - Changes the HW's global state. +- unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; ++ unsafe fn enable_mmu_and_caching( ++ &self, ++ phys_tables_base_addr: Address, ++ ) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; +@@ -65,55 +61,51 @@ + /// Describes properties of an address space. + pub struct AddressSpace; + +-/// Architecture agnostic translation types. +-#[allow(missing_docs)] +-#[derive(Copy, Clone)] +-pub enum Translation { +- Identity, +- Offset(usize), +-} +- +-/// Architecture agnostic memory attributes. +-#[allow(missing_docs)] +-#[derive(Copy, Clone)] +-pub enum MemAttributes { +- CacheableDRAM, +- Device, +-} +- +-/// Architecture agnostic access permissions. +-#[allow(missing_docs)] +-#[derive(Copy, Clone)] +-pub enum AccessPermissions { +- ReadOnly, +- ReadWrite, +-} +- +-/// Collection of memory attributes. +-#[allow(missing_docs)] +-#[derive(Copy, Clone)] +-pub struct AttributeFields { +- pub mem_attributes: MemAttributes, +- pub acc_perms: AccessPermissions, +- pub execute_never: bool, ++/// Intended to be implemented for [`AddressSpace`]. ++pub trait AssociatedTranslationTable { ++ /// A translation table whose address range is: ++ /// ++ /// [AS_SIZE - 1, 0] ++ type TableStartFromBottom; + } + +-/// Architecture agnostic descriptor for a memory range. +-#[allow(missing_docs)] +-pub struct TranslationDescriptor { +- pub name: &'static str, +- pub virtual_range: fn() -> RangeInclusive, +- pub physical_range_translation: Translation, +- pub attribute_fields: AttributeFields, +-} ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++use interface::MMU; ++use synchronization::interface::*; ++use translation_table::interface::TranslationTable; ++ ++/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's ++/// MMIO VA allocator with it. ++fn kernel_init_mmio_va_allocator() { ++ let region = bsp::memory::mmu::virt_mmio_remap_region(); ++ ++ page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); ++} ++ ++/// Map a region in the kernel's translation tables. ++/// ++/// No input checks done, input is passed through to the architectural implementation. ++/// ++/// # Safety ++/// ++/// - See `map_at()`. ++/// - Does not prevent aliasing. ++unsafe fn kernel_map_at_unchecked( ++ name: &'static str, ++ virt_region: &MemoryRegion, ++ phys_region: &MemoryRegion, ++ attr: &AttributeFields, ++) -> Result<(), &'static str> { ++ bsp::memory::mmu::kernel_translation_tables() ++ .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + +-/// Type for expressing the kernel's virtual memory layout. +-pub struct KernelVirtualLayout { +- /// The last (inclusive) address of the address space. +- max_virt_addr_inclusive: usize, ++ if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { ++ warn!("{}", x); ++ } + +- /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. +- inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], ++ Ok(()) + } + + //-------------------------------------------------------------------------------------------------- +@@ -133,6 +125,9 @@ + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + ++ /// The granule's mask. ++ pub const MASK: usize = Self::SIZE - 1; ++ + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + +@@ -160,98 +155,147 @@ + } + } + +-impl Default for AttributeFields { +- fn default() -> AttributeFields { +- AttributeFields { +- mem_attributes: MemAttributes::CacheableDRAM, +- acc_perms: AccessPermissions::ReadWrite, +- execute_never: true, +- } ++/// Raw mapping of a virtual to physical region in the kernel translation tables. ++/// ++/// Prevents mapping into the MMIO range of the tables. ++/// ++/// # Safety ++/// ++/// - See `kernel_map_at_unchecked()`. ++/// - Does not prevent aliasing. Currently, the callers must be trusted. ++pub unsafe fn kernel_map_at( ++ name: &'static str, ++ virt_region: &MemoryRegion, ++ phys_region: &MemoryRegion, ++ attr: &AttributeFields, ++) -> Result<(), &'static str> { ++ if bsp::memory::mmu::virt_mmio_remap_region().overlaps(virt_region) { ++ return Err("Attempt to manually map into MMIO region"); + } +-} + +-/// Human-readable output of a TranslationDescriptor. +-impl fmt::Display for TranslationDescriptor { +- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +- // Call the function to which self.range points, and dereference the result, which causes +- // Rust to copy the value. +- let start = *(self.virtual_range)().start(); +- let end = *(self.virtual_range)().end(); +- let size = end - start + 1; +- +- let (size, unit) = common::size_human_readable_ceil(size); +- +- let attr = match self.attribute_fields.mem_attributes { +- MemAttributes::CacheableDRAM => "C", +- MemAttributes::Device => "Dev", +- }; +- +- let acc_p = match self.attribute_fields.acc_perms { +- AccessPermissions::ReadOnly => "RO", +- AccessPermissions::ReadWrite => "RW", +- }; ++ kernel_map_at_unchecked(name, virt_region, phys_region, attr)?; + +- let xn = if self.attribute_fields.execute_never { +- "PXN" +- } else { +- "PX" +- }; +- +- write!( +- f, +- " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", +- start, end, size, unit, attr, acc_p, xn, self.name +- ) +- } ++ Ok(()) + } + +-impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { +- /// Create a new instance. +- pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { +- Self { +- max_virt_addr_inclusive: max, +- inner: layout, +- } +- } ++/// MMIO remapping in the kernel translation tables. ++/// ++/// Typically used by device drivers. ++/// ++/// # Safety ++/// ++/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. ++pub unsafe fn kernel_map_mmio( ++ name: &'static str, ++ mmio_descriptor: &MMIODescriptor, ++) -> Result, &'static str> { ++ let phys_region = MemoryRegion::from(*mmio_descriptor); ++ let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); ++ ++ // Check if an identical region has been mapped for another driver. If so, reuse it. ++ let virt_addr = if let Some(addr) = ++ mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) ++ { ++ addr ++ // Otherwise, allocate a new region and map it. ++ } else { ++ let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { ++ None => return Err("Requested 0 pages"), ++ Some(x) => x, ++ }; + +- /// For a virtual address, find and return the physical output address and corresponding +- /// attributes. +- /// +- /// If the address is not found in `inner`, return an identity mapped default with normal +- /// cacheable DRAM attributes. +- pub fn virt_addr_properties( +- &self, +- virt_addr: usize, +- ) -> Result<(usize, AttributeFields), &'static str> { +- if virt_addr > self.max_virt_addr_inclusive { +- return Err("Address out of range"); +- } ++ let virt_region = ++ page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + +- for i in self.inner.iter() { +- if (i.virtual_range)().contains(&virt_addr) { +- let output_addr = match i.physical_range_translation { +- Translation::Identity => virt_addr, +- Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), +- }; ++ kernel_map_at_unchecked( ++ name, ++ &virt_region, ++ &phys_region, ++ &AttributeFields { ++ mem_attributes: MemAttributes::Device, ++ acc_perms: AccessPermissions::ReadWrite, ++ execute_never: true, ++ }, ++ )?; ++ ++ virt_region.start_addr() ++ }; ++ ++ Ok(virt_addr + offset_into_start_page) ++} ++ ++/// Map the kernel's binary. Returns the translation table's base address. ++/// ++/// # Safety ++/// ++/// - See [`bsp::memory::mmu::kernel_map_binary()`]. ++pub unsafe fn kernel_map_binary() -> Result, &'static str> { ++ let phys_kernel_tables_base_addr = ++ bsp::memory::mmu::kernel_translation_tables().write(|tables| { ++ tables.init(); ++ tables.phys_base_address() ++ }); ++ ++ bsp::memory::mmu::kernel_map_binary()?; ++ ++ Ok(phys_kernel_tables_base_addr) ++} ++ ++/// Enable the MMU and data + instruction caching. ++/// ++/// # Safety ++/// ++/// - Crucial function during kernel init. Changes the the complete memory view of the processor. ++pub unsafe fn enable_mmu_and_caching( ++ phys_tables_base_addr: Address, ++) -> Result<(), MMUEnableError> { ++ arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) ++} ++ ++/// Finish initialization of the MMU subsystem. ++pub fn post_enable_init() { ++ kernel_init_mmio_va_allocator(); ++} ++ ++/// Human-readable print of all recorded kernel mappings. ++pub fn kernel_print_mappings() { ++ mapping_record::kernel_print() ++} + +- return Ok((output_addr, i.attribute_fields)); +- } +- } ++//-------------------------------------------------------------------------------------------------- ++// Testing ++//-------------------------------------------------------------------------------------------------- + +- Ok((virt_addr, AttributeFields::default())) +- } ++#[cfg(test)] ++mod tests { ++ use super::*; ++ use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; ++ use test_macros::kernel_test; + +- /// Print the memory layout. +- pub fn print_layout(&self) { +- use crate::info; ++ /// Check that you cannot map into the MMIO VA range from kernel_map_at(). ++ #[kernel_test] ++ fn no_manual_mmio_map() { ++ let phys_start_page_addr: PageAddress = PageAddress::from(0); ++ let phys_end_exclusive_page_addr: PageAddress = ++ phys_start_page_addr.checked_offset(5).unwrap(); ++ let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); ++ ++ let num_pages = NonZeroUsize::new(phys_region.num_pages()).unwrap(); ++ let virt_region = page_alloc::kernel_mmio_va_allocator() ++ .lock(|allocator| allocator.alloc(num_pages)) ++ .unwrap(); + +- for i in self.inner.iter() { +- info!("{}", i); +- } +- } ++ let attr = AttributeFields { ++ mem_attributes: MemAttributes::CacheableDRAM, ++ acc_perms: AccessPermissions::ReadWrite, ++ execute_never: true, ++ }; + +- #[cfg(test)] +- pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { +- &self.inner ++ unsafe { ++ assert_eq!( ++ kernel_map_at("test", &virt_region, &phys_region, &attr), ++ Err("Attempt to manually map into MMIO region") ++ ) ++ }; + } + } + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs +@@ -5,3 +5,163 @@ + //! Memory Management. + + pub mod mmu; ++ ++use crate::{bsp, common}; ++use core::{ ++ fmt, ++ marker::PhantomData, ++ ops::{Add, Sub}, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Metadata trait for marking the type of an address. ++pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} ++ ++/// Zero-sized type to mark a physical address. ++#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] ++pub enum Physical {} ++ ++/// Zero-sized type to mark a virtual address. ++#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] ++pub enum Virtual {} ++ ++/// Generic address type. ++#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] ++pub struct Address { ++ value: usize, ++ _address_type: PhantomData ATYPE>, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl AddressType for Physical {} ++impl AddressType for Virtual {} ++ ++impl Address { ++ /// Create an instance. ++ pub const fn new(value: usize) -> Self { ++ Self { ++ value, ++ _address_type: PhantomData, ++ } ++ } ++ ++ /// Convert to usize. ++ pub const fn as_usize(self) -> usize { ++ self.value ++ } ++ ++ /// Align down to page size. ++ #[must_use] ++ pub const fn align_down_page(self) -> Self { ++ let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); ++ ++ Self::new(aligned) ++ } ++ ++ /// Align up to page size. ++ #[must_use] ++ pub const fn align_up_page(self) -> Self { ++ let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); ++ ++ Self::new(aligned) ++ } ++ ++ /// Checks if the address is page aligned. ++ pub const fn is_page_aligned(&self) -> bool { ++ common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) ++ } ++ ++ /// Return the address' offset into the corresponding page. ++ pub const fn offset_into_page(&self) -> usize { ++ self.value & bsp::memory::mmu::KernelGranule::MASK ++ } ++} ++ ++impl Add for Address { ++ type Output = Self; ++ ++ #[inline(always)] ++ fn add(self, rhs: usize) -> Self::Output { ++ match self.value.checked_add(rhs) { ++ None => panic!("Overflow on Address::add"), ++ Some(x) => Self::new(x), ++ } ++ } ++} ++ ++impl Sub> for Address { ++ type Output = Self; ++ ++ #[inline(always)] ++ fn sub(self, rhs: Address) -> Self::Output { ++ match self.value.checked_sub(rhs.value) { ++ None => panic!("Overflow on Address::sub"), ++ Some(x) => Self::new(x), ++ } ++ } ++} ++ ++impl fmt::Display for Address { ++ // Don't expect to see physical addresses greater than 40 bit. ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ let q3: u8 = ((self.value >> 32) & 0xff) as u8; ++ let q2: u16 = ((self.value >> 16) & 0xffff) as u16; ++ let q1: u16 = (self.value & 0xffff) as u16; ++ ++ write!(f, "0x")?; ++ write!(f, "{:02x}_", q3)?; ++ write!(f, "{:04x}_", q2)?; ++ write!(f, "{:04x}", q1) ++ } ++} ++ ++impl fmt::Display for Address { ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ let q4: u16 = ((self.value >> 48) & 0xffff) as u16; ++ let q3: u16 = ((self.value >> 32) & 0xffff) as u16; ++ let q2: u16 = ((self.value >> 16) & 0xffff) as u16; ++ let q1: u16 = (self.value & 0xffff) as u16; ++ ++ write!(f, "0x")?; ++ write!(f, "{:04x}_", q4)?; ++ write!(f, "{:04x}_", q3)?; ++ write!(f, "{:04x}_", q2)?; ++ write!(f, "{:04x}", q1) ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Testing ++//-------------------------------------------------------------------------------------------------- ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ use test_macros::kernel_test; ++ ++ /// Sanity of [Address] methods. ++ #[kernel_test] ++ fn address_type_method_sanity() { ++ let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); ++ ++ assert_eq!( ++ addr.align_down_page().as_usize(), ++ bsp::memory::mmu::KernelGranule::SIZE ++ ); ++ ++ assert_eq!( ++ addr.align_up_page().as_usize(), ++ bsp::memory::mmu::KernelGranule::SIZE * 2 ++ ); ++ ++ assert!(!addr.is_page_aligned()); ++ ++ assert_eq!(addr.offset_into_page(), 100); ++ } ++} + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs +@@ -11,13 +11,24 @@ + /// Console tests should time out on the I/O harness in case of panic. + mod panic_wait_forever; + +-use libkernel::{bsp, console, cpu, exception, print}; ++use libkernel::{bsp, console, cpu, exception, memory, print}; + + #[no_mangle] + unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); ++ ++ let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { ++ Err(string) => panic!("Error mapping kernel binary: {}", string), ++ Ok(addr) => addr, ++ }; ++ ++ if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { ++ panic!("Enabling MMU failed: {}", e); ++ } ++ ++ memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs +@@ -11,12 +11,23 @@ + #![test_runner(libkernel::test_runner)] + + use core::time::Duration; +-use libkernel::{bsp, cpu, exception, time}; ++use libkernel::{bsp, cpu, exception, memory, time}; + use test_macros::kernel_test; + + #[no_mangle] + unsafe fn kernel_init() -> ! { + exception::handling_init(); ++ ++ let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { ++ Err(string) => panic!("Error mapping kernel binary: {}", string), ++ Ok(addr) => addr, ++ }; ++ ++ if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { ++ panic!("Enabling MMU failed: {}", e); ++ } ++ ++ memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs +@@ -21,19 +21,27 @@ + + #[no_mangle] + unsafe fn kernel_init() -> ! { +- use memory::mmu::interface::MMU; +- + exception::handling_init(); +- bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + +- if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { +- info!("MMU: {}", string); ++ let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { ++ Err(string) => { ++ info!("Error mapping kernel binary: {}", string); ++ cpu::qemu_exit_failure() ++ } ++ Ok(addr) => addr, ++ }; ++ ++ if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { ++ info!("Enabling MMU failed: {}", e); + cpu::qemu_exit_failure() + } + ++ memory::mmu::post_enable_init(); ++ bsp::driver::qemu_bring_up_console(); ++ + info!("Writing beyond mapped area to address 9 GiB..."); + let big_addr: u64 = 9 * 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs +@@ -30,19 +30,27 @@ + + #[no_mangle] + unsafe fn kernel_init() -> ! { +- use memory::mmu::interface::MMU; +- + exception::handling_init(); +- bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + +- if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { +- info!("MMU: {}", string); ++ let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { ++ Err(string) => { ++ info!("Error mapping kernel binary: {}", string); ++ cpu::qemu_exit_failure() ++ } ++ Ok(addr) => addr, ++ }; ++ ++ if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { ++ info!("Enabling MMU failed: {}", e); + cpu::qemu_exit_failure() + } + ++ memory::mmu::post_enable_init(); ++ bsp::driver::qemu_bring_up_console(); ++ + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + +diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs +--- 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs ++++ 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs +@@ -10,14 +10,25 @@ + #![reexport_test_harness_main = "test_main"] + #![test_runner(libkernel::test_runner)] + +-use libkernel::{bsp, cpu, exception}; ++use libkernel::{bsp, cpu, exception, memory}; + use test_macros::kernel_test; + + #[no_mangle] + unsafe fn kernel_init() -> ! { ++ exception::handling_init(); ++ ++ let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { ++ Err(string) => panic!("Error mapping kernel binary: {}", string), ++ Ok(addr) => addr, ++ }; ++ ++ if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { ++ panic!("Enabling MMU failed: {}", e); ++ } ++ ++ memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + +- exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + +``` diff --git a/14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml b/14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml new file mode 100644 index 000000000..b85ecbede --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml @@ -0,0 +1,57 @@ +[package] +name = "mingo" +version = "0.14.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##-------------------------------------------------------------------------------------------------- +## Testing +##-------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false diff --git a/14_virtual_mem_part2_mmio_remap/kernel/build.rs b/14_virtual_mem_part2_mmio_remap/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..c80f3ebbc --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(crate::kernel_init as *const () as u64); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..f6df21236 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. x0 holds the function argument provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/smp.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/smp.rs new file mode 100644 index 000000000..491920389 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..730198009 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use crate::exception; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!(include_str!("exception.s")); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.s b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..91805ee7c --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 17 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception/asynchronous.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..811ef138e --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..e0717a7f5 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::{mmu::TranslationGranule, Address, Physical}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + fn configure_translation_control(&self) { + let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI0::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG0::KiB_64 + + TCR_EL1::SH0::Inner + + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD0::EnableTTBR0Walks + + TCR_EL1::A1::TTBR0 + + TCR_EL1::T0SZ.val(t0sz) + + TCR_EL1::EPD1::DisableTTBR1Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Set the "Translation Table Base Register". + TTBR0_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..2d87543c8 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,406 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, + memory::{ + self, + mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, + }, + Address, Physical, Virtual, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn phys_start_addr(&self) -> Address; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], + + /// Have the tables been initialized? + initialized: bool, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +// The binary is still identity mapped, so we don't need to convert here. +impl StartAddr for [T; N] { + fn phys_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_page_addr( + phys_output_page_addr: PageAddress, + attribute_fields: &AttributeFields, + ) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } + + /// Returns the valid bit. + fn is_valid(&self) -> bool { + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }>; +} + +impl FixedSizeTranslationTable { + /// Create an instance. + #[allow(clippy::assertions_on_constants)] + pub const fn new() -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + initialized: false, + } + } + + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { + let addr = virt_page_addr.into_inner().as_usize(); + let lvl2_index = addr >> Granule512MiB::SHIFT; + let lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); + } + + Ok((lvl2_index, lvl3_index)) + } + + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. + #[inline(always)] + fn set_page_descriptor_from_page_addr( + &mut self, + virt_page_addr: PageAddress, + new_desc: &PageDescriptor, + ) -> Result<(), &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &mut self.lvl3[lvl2_index][lvl3_index]; + + if desc.is_valid() { + return Err("Virtual page is already mapped"); + } + + *desc = *new_desc; + Ok(()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable +{ + fn init(&mut self) { + if self.initialized { + return; + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { + let phys_table_addr = self.lvl3[lvl2_nr].phys_start_addr(); + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; + } + + fn phys_base_address(&self) -> Address { + self.lvl2.phys_start_addr() + } + + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + assert!(self.initialized, "Translation tables not initialized"); + + if virt_region.size() != phys_region.size() { + return Err("Tried to map memory regions with unequal sizes"); + } + + if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() + { + return Err("Tried to map outside of physical address space"); + } + + let iter = phys_region.into_iter().zip(virt_region.into_iter()); + for (phys_page_addr, virt_page_addr) in iter { + let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); + let virt_page = virt_page_addr; + + self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1>; + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/time.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..2dfaec8d6 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(feature = "bsp_rpi4")] +mod arm; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm.rs new file mode 100644 index 000000000..8d1cbfbd8 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs new file mode 100644 index 000000000..256de7041 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new( + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, + ) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs new file mode 100644 index 000000000..0fd16bb38 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs new file mode 100644 index 000000000..1fc9d70e9 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, + state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num % 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..7b7c288b7 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..812156f44 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs new file mode 100644 index 000000000..62f078002 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.periph.print_handler(); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs new file mode 100644 index 000000000..a26bff8d0 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), + } + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() % 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..b424d4be7 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/common.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..3ce1d8d81 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use crate::memory::{Address, Virtual}; +use core::{fmt, marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: Address, + phantom: PhantomData T>, +} + +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: Address) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr.as_usize() as *const _) } + } +} + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..30421dfa6 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/cpu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/driver.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..a1f55b170 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, + memory, + memory::mmu::MMIODescriptor, +}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering}, +}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi3")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi4")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the UART driver. +unsafe fn post_init_uart() -> Result<(), &'static str> { + console::register_console(PL011_UART.assume_init_ref()); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_gpio() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; + + GPIO.write(device_driver::GPIO::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +unsafe fn post_init_gpio() -> Result<(), &'static str> { + GPIO.assume_init_ref().map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi3")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &periph_mmio_descriptor, + )?; + + INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi4")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); + let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; + + let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); + let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; + + INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the interrupt controller driver. +unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_gpio() -> Result<(), &'static str> { + instantiate_gpio()?; + + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( + GPIO.assume_init_ref(), + Some(post_init_gpio), + None, + ); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { + instantiate_interrupt_controller()?; + + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + INTERRUPT_CONTROLLER.assume_init_ref(), + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + use crate::cpu; + + unsafe { + instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); + console::register_console(PL011_UART.assume_init_ref()); + }; +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception.rs new file mode 100644 index 000000000..a9eaa6ac4 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs new file mode 100644 index 000000000..776182fd0 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +#[cfg(feature = "bsp_rpi3")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; + + pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +#[cfg(feature = "bsp_rpi4")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::IRQNumber; + + pub const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..3f5f7043e --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,101 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + __data_start = .; + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..0d963aa30 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | data_end_exclusive +//! | | +//! +//! +//! +//! +//! +//! The virtual memory layout is as follows: +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_start == data_end_exclusive +//! | VA region for MMIO remapping | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_end_exclusive +//! | | +pub mod mmu; + +use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; + + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + + static __boot_core_stack_start: UnsafeCell<()>; + static __boot_core_stack_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + use super::*; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); + pub const PERIPHERAL_IC_SIZE: usize = 0x24; + + pub const GPIO_START: Address = Address::new(0x3F20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const END: Address = Address::new(0x4001_0000); + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const GPIO_START: Address = Address::new(0xFE20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0xFE20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const GICD_START: Address = Address::new(0xFF84_1000); + pub const GICD_SIZE: usize = 0x824; + + pub const GICC_START: Address = Address::new(0xFF84_2000); + pub const GICC_SIZE: usize = 0x14; + + pub const END: Address = Address::new(0xFF85_0000); + } + + pub const END: Address = mmio::END; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_code_start() -> PageAddress { + PageAddress::from(unsafe { __code_start.get() as usize }) +} + +/// Size of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_size() -> usize { + unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } +} + +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { + PageAddress::from(unsafe { __data_start.get() as usize }) +} + +/// Size of the data segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn data_size() -> usize { + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } +} + +/// Start page address of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_mmio_remap_start() -> PageAddress { + PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) +} + +/// Size of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn mmio_remap_size() -> usize { + unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } +} + +/// Start page address of the boot core's stack. +#[inline(always)] +fn virt_boot_core_stack_start() -> PageAddress { + PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) +} + +/// Size of the boot core's stack. +#[inline(always)] +fn boot_core_stack_size() -> usize { + unsafe { + (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Exclusive end address of the physical address space. +#[inline(always)] +pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { + PageAddress::from(map::END) +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..86a118c3f --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use crate::{ + memory::{ + mmu::{ + self as generic_mmu, AccessPermissions, AddressSpace, AssociatedTranslationTable, + AttributeFields, MemAttributes, MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type KernelTranslationTable = + ::TableStartFromBottom; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to +/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. +pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + +/// The kernel's virtual address space defined by this BSP. +pub type KernelVirtAddrSpace = AddressSpace<{ 1024 * 1024 * 1024 }>; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// It is mandatory that InitStateLock is transparent. +/// +/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. +/// There is a unit tests that checks this porperty. +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Helper function for calculating the number of pages the given parameter spans. +const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); + assert!(size % KernelGranule::SIZE == 0); + + size >> KernelGranule::SHIFT +} + +/// The code pages of the kernel binary. +fn virt_code_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::code_size()); + + let start_page_addr = super::virt_code_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The data pages of the kernel binary. +fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); + + let start_page_addr = super::virt_data_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The boot core stack pages. +fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); + + let start_page_addr = super::virt_boot_core_stack_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +// The binary is still identity mapped, so use this trivial conversion function for mapping below. + +fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { + MemoryRegion::new( + PageAddress::from(virt_region.start_page_addr().into_inner().as_usize()), + PageAddress::from( + virt_region + .end_exclusive_page_addr() + .into_inner() + .as_usize(), + ), + ) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} + +/// The MMIO remap pages. +pub fn virt_mmio_remap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::mmio_remap_size()); + + let start_page_addr = super::virt_mmio_remap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Map the kernel binary. +/// +/// # Safety +/// +/// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking. +pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { + generic_mmu::kernel_map_at( + "Kernel boot-core stack", + &virt_boot_core_stack_region(), + &kernel_virt_to_phys_region(virt_boot_core_stack_region()), + &AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + generic_mmu::kernel_map_at( + "Kernel code and RO data", + &virt_code_region(), + &kernel_virt_to_phys_region(virt_code_region()), + &AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadOnly, + execute_never: false, + }, + )?; + + generic_mmu::kernel_map_at( + "Kernel data and bss", + &virt_data_region(), + &kernel_virt_to_phys_region(virt_data_region()), + &AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use core::{cell::UnsafeCell, ops::Range}; + use test_macros::kernel_test; + + /// Check alignment of the kernel's virtual memory layout sections. + #[kernel_test] + fn virt_mem_layout_sections_are_64KiB_aligned() { + for i in [ + virt_boot_core_stack_region, + virt_code_region, + virt_data_region, + ] + .iter() + { + let start = i().start_page_addr().into_inner(); + let end_exclusive = i().end_exclusive_page_addr().into_inner(); + + assert!(start.is_page_aligned()); + assert!(end_exclusive.is_page_aligned()); + assert!(end_exclusive >= start); + } + } + + /// Ensure the kernel's virtual memory layout is free of overlaps. + #[kernel_test] + fn virt_mem_layout_has_no_overlaps() { + let layout = [ + virt_boot_core_stack_region(), + virt_code_region(), + virt_data_region(), + ]; + + for (i, first_range) in layout.iter().enumerate() { + for second_range in layout.iter().skip(i + 1) { + assert!(!first_range.overlaps(second_range)) + } + } + } + + /// Check if KERNEL_TABLES is in .bss. + #[kernel_test] + fn kernel_tables_in_bss() { + extern "Rust" { + static __bss_start: UnsafeCell; + static __bss_end_exclusive: UnsafeCell; + } + + let bss_range = unsafe { + Range { + start: __bss_start.get(), + end: __bss_end_exclusive.get(), + } + }; + let kernel_tables_addr = &KERNEL_TABLES as *const _ as usize as *mut u64; + + assert!(bss_range.contains(&kernel_tables_addr)); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/common.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/common.rs new file mode 100644 index 000000000..2ad7e4c1e --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/common.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Check if a value is aligned to a given size. +#[inline(always)] +pub const fn is_aligned(value: usize, alignment: usize) -> bool { + assert!(alignment.is_power_of_two()); + + (value & (alignment - 1)) == 0 +} + +/// Align down. +#[inline(always)] +pub const fn align_down(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + value & !(alignment - 1) +} + +/// Align up. +#[inline(always)] +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + (value + alignment - 1) & !(alignment - 1) +} + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/console.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/console.rs new file mode 100644 index 000000000..f03634649 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.read(|con| *con) +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/console/null_console.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/cpu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu.rs new file mode 100644 index 000000000..8716a918b --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +pub mod smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/boot.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/smp.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/smp.rs new file mode 100644 index 000000000..de612d589 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/driver.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/driver.rs new file mode 100644 index 000000000..2edf8b854 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/driver.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner +where + T: 'static, +{ + next_index: usize, + descriptors: [Option>; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager +where + T: 'static, +{ + inner: InitStateLock>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner +where + T: 'static + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + irq_number, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager +where + T: fmt::Display + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: InitStateLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.write(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.read(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + self.for_each_descriptor(|descriptor| { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/exception.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..2c874dd60 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous/null_irq_manager.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous/null_irq_manager.rs new file mode 100644 index 000000000..38919ffe4 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs new file mode 100644 index 000000000..fef85dfbe --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs @@ -0,0 +1,206 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(generic_const_exprs)] +#![feature(int_roundings)] +#![feature(is_sorted)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(step_trait)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +mod panic_wait; +mod synchronization; + +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod state; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +#[cfg(not(test))] +extern "Rust" { + fn kernel_init() -> !; +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/main.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/main.rs new file mode 100644 index 000000000..b76b003c7 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/main.rs @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + +/// Early init code. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order: +/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, +/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ +/// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online:"); + memory::mmu::kernel_print_mappings(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + + info!("Echoing input now"); + cpu::wait_forever(); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs new file mode 100644 index 000000000..b2638470d --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; + +use crate::{bsp, common}; +use core::{ + fmt, + marker::PhantomData, + ops::{Add, Sub}, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Physical {} + +/// Zero-sized type to mark a virtual address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl AddressType for Physical {} +impl AddressType for Virtual {} + +impl Address { + /// Create an instance. + pub const fn new(value: usize) -> Self { + Self { + value, + _address_type: PhantomData, + } + } + + /// Convert to usize. + pub const fn as_usize(self) -> usize { + self.value + } + + /// Align down to page size. + #[must_use] + pub const fn align_down_page(self) -> Self { + let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Align up to page size. + #[must_use] + pub const fn align_up_page(self) -> Self { + let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Checks if the address is page aligned. + pub const fn is_page_aligned(&self) -> bool { + common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) + } + + /// Return the address' offset into the corresponding page. + pub const fn offset_into_page(&self) -> usize { + self.value & bsp::memory::mmu::KernelGranule::MASK + } +} + +impl Add for Address { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: usize) -> Self::Output { + match self.value.checked_add(rhs) { + None => panic!("Overflow on Address::add"), + Some(x) => Self::new(x), + } + } +} + +impl Sub> for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Address) -> Self::Output { + match self.value.checked_sub(rhs.value) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q3: u8 = ((self.value >> 32) & 0xff) as u8; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:02x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q4: u16 = ((self.value >> 48) & 0xffff) as u16; + let q3: u16 = ((self.value >> 32) & 0xffff) as u16; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:04x}_", q4)?; + write!(f, "{:04x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of [Address] methods. + #[kernel_test] + fn address_type_method_sanity() { + let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); + + assert_eq!( + addr.align_down_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE + ); + + assert_eq!( + addr.align_up_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + + assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..20e35def2 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs @@ -0,0 +1,301 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod mapping_record; +mod page_alloc; +mod translation_table; +mod types; + +use crate::{ + bsp, + memory::{Address, Physical, Virtual}, + synchronization, warn, +}; +use core::{fmt, num::NonZeroUsize}; + +pub use types::*; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Turns on the MMU for the first time and enables data and instruction caching. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +use interface::MMU; +use synchronization::interface::*; +use translation_table::interface::TranslationTable; + +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Map a region in the kernel's translation tables. +/// +/// No input checks done, input is passed through to the architectural implementation. +/// +/// # Safety +/// +/// - See `map_at()`. +/// - Does not prevent aliasing. +unsafe fn kernel_map_at_unchecked( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + + if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { + warn!("{}", x); + } + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's mask. + pub const MASK: usize = Self::SIZE - 1; + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +/// Raw mapping of a virtual to physical region in the kernel translation tables. +/// +/// Prevents mapping into the MMIO range of the tables. +/// +/// # Safety +/// +/// - See `kernel_map_at_unchecked()`. +/// - Does not prevent aliasing. Currently, the callers must be trusted. +pub unsafe fn kernel_map_at( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + if bsp::memory::mmu::virt_mmio_remap_region().overlaps(virt_region) { + return Err("Attempt to manually map into MMIO region"); + } + + kernel_map_at_unchecked(name, virt_region, phys_region, attr)?; + + Ok(()) +} + +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +/// +/// # Safety +/// +/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + let phys_region = MemoryRegion::from(*mmio_descriptor); + let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); + + // Check if an identical region has been mapped for another driver. If so, reuse it. + let virt_addr = if let Some(addr) = + mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) + { + addr + // Otherwise, allocate a new region and map it. + } else { + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, + }; + + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + virt_region.start_addr() + }; + + Ok(virt_addr + offset_into_start_page) +} + +/// Map the kernel's binary. Returns the translation table's base address. +/// +/// # Safety +/// +/// - See [`bsp::memory::mmu::kernel_map_binary()`]. +pub unsafe fn kernel_map_binary() -> Result, &'static str> { + let phys_kernel_tables_base_addr = + bsp::memory::mmu::kernel_translation_tables().write(|tables| { + tables.init(); + tables.phys_base_address() + }); + + bsp::memory::mmu::kernel_map_binary()?; + + Ok(phys_kernel_tables_base_addr) +} + +/// Enable the MMU and data + instruction caching. +/// +/// # Safety +/// +/// - Crucial function during kernel init. Changes the the complete memory view of the processor. +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) +} + +/// Finish initialization of the MMU subsystem. +pub fn post_enable_init() { + kernel_init_mmio_va_allocator(); +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use test_macros::kernel_test; + + /// Check that you cannot map into the MMIO VA range from kernel_map_at(). + #[kernel_test] + fn no_manual_mmio_map() { + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let num_pages = NonZeroUsize::new(phys_region.num_pages()).unwrap(); + let virt_region = page_alloc::kernel_mmio_va_allocator() + .lock(|allocator| allocator.alloc(num_pages)) + .unwrap(); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { + assert_eq!( + kernel_map_at("test", &virt_region, &phys_region, &attr), + Err("Attempt to manually map into MMIO region") + ) + }; + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs new file mode 100644 index 000000000..0e0792201 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + +use super::{ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Type describing a virtual memory mapping. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +struct MappingRecordEntry { + pub users: [Option<&'static str>; 5], + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, + pub attribute_fields: AttributeFields, +} + +struct MappingRecord { + inner: [Option; 12], +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MAPPING_RECORD: InitStateLock = + InitStateLock::new(MappingRecord::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl MappingRecordEntry { + pub fn new( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Self { + Self { + users: [Some(name), None, None, None, None], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), + attribute_fields: *attr, + } + } + + fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { + if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { + return Ok(x); + }; + + Err("Storage for user info exhausted") + } + + pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { + let x = self.find_next_free_user()?; + *x = Some(user); + Ok(()) + } +} + +impl MappingRecord { + pub const fn new() -> Self { + Self { inner: [None; 12] } + } + + fn size(&self) -> usize { + self.inner.iter().filter(|x| x.is_some()).count() + } + + fn sort(&mut self) { + let upper_bound_exclusive = self.size(); + let entries = &mut self.inner[0..upper_bound_exclusive]; + + if !entries.is_sorted_by_key(|item| item.unwrap().virt_start_addr) { + entries.sort_unstable_by_key(|item| item.unwrap().virt_start_addr) + } + } + + fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { + if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { + return Ok(x); + } + + Err("Storage for mapping info exhausted") + } + + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() + .filter_map(|x| x.as_mut()) + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { + return false; + } + + if x.num_pages != phys_region.num_pages() { + return false; + } + + true + }) + } + + pub fn add( + &mut self, + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + let x = self.find_next_free()?; + + *x = Some(MappingRecordEntry::new( + name, + virt_region, + phys_region, + attr, + )); + + self.sort(); + + Ok(()) + } + + pub fn print(&self) { + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", + "Virtual", "Physical", "Size", "Attr", "Entity" + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + + for i in self.inner.iter().flatten() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match i.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if i.attribute_fields.execute_never { + "XN" + } else { + "X" + }; + + info!( + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, + phys_end_inclusive, + size, + unit, + attr, + acc_p, + xn, + i.users[0].unwrap() + ); + + for k in i.users[1..].iter() { + if let Some(additional_user) = *k { + info!( + " | {}", + additional_user + ); + } + } + } + + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +/// Add an entry to the mapping info record. +pub fn kernel_add( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) +} + +pub fn kernel_find_and_insert_mmio_duplicate( + mmio_descriptor: &MMIODescriptor, + new_user: &'static str, +) -> Option> { + let phys_region: MemoryRegion = (*mmio_descriptor).into(); + + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + + if let Err(x) = dup.add_user(new_user) { + warn!("{}", x); + } + + Some(dup.virt_start_addr) + }) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print() { + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs new file mode 100644 index 000000000..344afd200 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Page allocation. + +use super::MemoryRegion; +use crate::{ + memory::{AddressType, Virtual}, + synchronization::IRQSafeNullLock, + warn, +}; +use core::num::NonZeroUsize; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A page allocator that can be lazyily initialized. +pub struct PageAllocator { + pool: Option>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = + IRQSafeNullLock::new(PageAllocator::new()); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's MMIO virtual address allocator. +pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { + &KERNEL_MMIO_VA_ALLOCATOR +} + +impl PageAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { pool: None } + } + + /// Initialize the allocator. + pub fn init(&mut self, pool: MemoryRegion) { + if self.pool.is_some() { + warn!("Already initialized"); + return; + } + + self.pool = Some(pool); + } + + /// Allocate a number of pages. + pub fn alloc( + &mut self, + num_requested_pages: NonZeroUsize, + ) -> Result, &'static str> { + if self.pool.is_none() { + return Err("Allocator not initialized"); + } + + self.pool + .as_mut() + .unwrap() + .take_first_n_pages(num_requested_pages) + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..0445ab296 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +use super::{AttributeFields, MemoryRegion}; +use crate::memory::{Address, Physical, Virtual}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(target_arch = "aarch64")] +pub use arch_translation_table::FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Translation table interfaces. +pub mod interface { + use super::*; + + /// Translation table operations. + pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self); + + /// The translation table's base address to be used for programming the MMU. + fn phys_base_address(&self) -> Address; + + /// Map the given virtual memory region to the given physical memory region. + /// + /// # Safety + /// + /// - Using wrong attributes can cause multiple issues of different nature in the system. + /// - It is not required that the architectural implementation prevents aliasing. That is, + /// mapping to the same physical memory using multiple virtual addresses, which would + /// break Rust's ownership assumptions. This should be protected against in the kernel's + /// generic MMU code. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use arch_translation_table::MinSizeTranslationTable; + use interface::TranslationTable; + use test_macros::kernel_test; + + /// Sanity checks for the TranslationTable implementation. + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. + let mut tables = MinSizeTranslationTable::new(); + + tables.init(); + + let virt_start_page_addr: PageAddress = PageAddress::from(0); + let virt_end_exclusive_page_addr: PageAddress = + virt_start_page_addr.checked_offset(5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + + let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs new file mode 100644 index 000000000..8feee064b --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + +use crate::{ + bsp, common, + memory::{Address, AddressType, Physical}, +}; +use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct PageAddress { + inner: Address, +} + +/// A type that describes a region of memory in quantities of pages. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// An MMIO descriptor for use in device drivers. +#[derive(Copy, Clone)] +pub struct MMIODescriptor { + start_addr: Address, + end_addr_exclusive: Address, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------ +// PageAddress +//------------------------------------------------------------------------------ +impl PageAddress { + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + } + + /// Calculates the offset from the page address. + /// + /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * + /// page_size`. + pub fn checked_offset(self, count: isize) -> Option { + if count == 0 { + return Some(self); + } + + let delta = count + .unsigned_abs() + .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; + let result = if count.is_positive() { + self.inner.as_usize().checked_add(delta)? + } else { + self.inner.as_usize().checked_sub(delta)? + }; + + Some(Self { + inner: Address::new(result), + }) + } +} + +impl From for PageAddress { + fn from(addr: usize) -> Self { + assert!( + common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), + "Input usize not page aligned" + ); + + Self { + inner: Address::new(addr), + } + } +} + +impl From> for PageAddress { + fn from(addr: Address) -> Self { + assert!(addr.is_page_aligned(), "Input Address not page aligned"); + + Self { inner: addr } + } +} + +impl Step for PageAddress { + fn steps_between(start: &Self, end: &Self) -> Option { + if start > end { + return None; + } + + // Since start <= end, do unchecked arithmetic. + Some( + (end.inner.as_usize() - start.inner.as_usize()) + >> bsp::memory::mmu::KernelGranule::SHIFT, + ) + } + + fn forward_checked(start: Self, count: usize) -> Option { + start.checked_offset(count as isize) + } + + fn backward_checked(start: Self, count: usize) -> Option { + start.checked_offset(-(count as isize)) + } +} + +//------------------------------------------------------------------------------ +// MemoryRegion +//------------------------------------------------------------------------------ +impl MemoryRegion { + /// Create an instance. + pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { + assert!(start <= end_exclusive); + + Self { + start, + end_exclusive, + } + } + + fn as_range(&self) -> Range> { + self.into_iter() + } + + /// Returns the start page address. + pub fn start_page_addr(&self) -> PageAddress { + self.start + } + + /// Returns the start address. + pub fn start_addr(&self) -> Address { + self.start.into_inner() + } + + /// Returns the exclusive end page address. + pub fn end_exclusive_page_addr(&self) -> PageAddress { + self.end_exclusive + } + + /// Returns the exclusive end page address. + pub fn end_inclusive_page_addr(&self) -> PageAddress { + self.end_exclusive.checked_offset(-1).unwrap() + } + + /// Checks if self contains an address. + pub fn contains(&self, addr: Address) -> bool { + let page_addr = PageAddress::from(addr.align_down_page()); + self.as_range().contains(&page_addr) + } + + /// Checks if there is an overlap with another memory region. + pub fn overlaps(&self, other_region: &Self) -> bool { + let self_range = self.as_range(); + + self_range.contains(&other_region.start_page_addr()) + || self_range.contains(&other_region.end_inclusive_page_addr()) + } + + /// Returns the number of pages contained in this region. + pub fn num_pages(&self) -> usize { + PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() + } + + /// Returns the size in bytes of this region. + pub fn size(&self) -> usize { + // Invariant: start <= end_exclusive, so do unchecked arithmetic. + let end_exclusive = self.end_exclusive.into_inner().as_usize(); + let start = self.start.into_inner().as_usize(); + + end_exclusive - start + } + + /// Splits the MemoryRegion like: + /// + /// -------------------------------------------------------------------------------- + /// | | | | | | | | | | | | | | | | | | | + /// -------------------------------------------------------------------------------- + /// ^ ^ ^ + /// | | | + /// left_start left_end_exclusive | + /// | + /// ^ | + /// | | + /// right_start right_end_exclusive + /// + /// Left region is returned to the caller. Right region is the new region for this struct. + pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { + let count: usize = num_pages.into(); + + let left_end_exclusive = self.start.checked_offset(count as isize); + let left_end_exclusive = match left_end_exclusive { + None => return Err("Overflow while calculating left_end_exclusive"), + Some(x) => x, + }; + + if left_end_exclusive > self.end_exclusive { + return Err("Not enough free pages"); + } + + let allocation = Self { + start: self.start, + end_exclusive: left_end_exclusive, + }; + self.start = left_end_exclusive; + + Ok(allocation) + } +} + +impl IntoIterator for MemoryRegion { + type Item = PageAddress; + type IntoIter = Range; + + fn into_iter(self) -> Self::IntoIter { + Range { + start: self.start, + end: self.end_exclusive, + } + } +} + +impl From for MemoryRegion { + fn from(desc: MMIODescriptor) -> Self { + let start = PageAddress::from(desc.start_addr.align_down_page()); + let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); + + Self { + start, + end_exclusive, + } + } +} + +//------------------------------------------------------------------------------ +// MMIODescriptor +//------------------------------------------------------------------------------ + +impl MMIODescriptor { + /// Create an instance. + pub const fn new(start_addr: Address, size: usize) -> Self { + assert!(size > 0); + let end_addr_exclusive = Address::new(start_addr.as_usize() + size); + + Self { + start_addr, + end_addr_exclusive, + } + } + + /// Return the start address. + pub const fn start_addr(&self) -> Address { + self.start_addr + } + + /// Return the exclusive end address. + pub fn end_addr_exclusive(&self) -> Address { + self.end_addr_exclusive + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::Virtual; + use test_macros::kernel_test; + + /// Sanity of [PageAddress] methods. + #[kernel_test] + fn pageaddress_type_method_sanity() { + let page_addr: PageAddress = + PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); + + assert_eq!( + page_addr.checked_offset(-2), + Some(PageAddress::::from(0)) + ); + + assert_eq!( + page_addr.checked_offset(2), + Some(PageAddress::::from( + bsp::memory::mmu::KernelGranule::SIZE * 4 + )) + ); + + assert_eq!( + PageAddress::::from(0).checked_offset(0), + Some(PageAddress::::from(0)) + ); + assert_eq!(PageAddress::::from(0).checked_offset(-1), None); + + let max_page_addr = Address::::new(usize::MAX).align_down_page(); + assert_eq!( + PageAddress::::from(max_page_addr).checked_offset(1), + None + ); + + let zero = PageAddress::::from(0); + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); + } + + /// Sanity of [MemoryRegion] methods. + #[kernel_test] + fn memoryregion_type_method_sanity() { + let zero = PageAddress::::from(0); + let zero_region = MemoryRegion::new(zero, zero); + assert_eq!(zero_region.num_pages(), 0); + assert_eq!(zero_region.size(), 0); + + let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); + let one_region = MemoryRegion::new(zero, one); + assert_eq!(one_region.num_pages(), 1); + assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); + + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + let mut three_region = MemoryRegion::new(zero, three); + assert!(three_region.contains(zero.into_inner())); + assert!(!three_region.contains(three.into_inner())); + assert!(three_region.overlaps(&one_region)); + + let allocation = three_region + .take_first_n_pages(NonZeroUsize::new(2).unwrap()) + .unwrap(); + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + + for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE + ); + } + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/panic_wait.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/panic_wait.rs new file mode 100644 index 000000000..c6f3a9c7b --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/panic_wait.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, exception, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + _panic_exit() +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/print.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/state.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/state.rs new file mode 100644 index 000000000..6d99beedb --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/synchronization.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/synchronization.rs new file mode 100644 index 000000000..5740b63e5 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/synchronization.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use crate::{exception, state}; + +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/src/time.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rb b/14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..d74091734 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, memory, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..c0a570e4a --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, memory, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..3abe91fcf --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => { + info!("Error mapping kernel binary: {}", string); + cpu::qemu_exit_failure() + } + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + info!("Enabling MMU failed: {}", e); + cpu::qemu_exit_failure() + } + + memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + info!("Writing beyond mapped area to address 9 GiB..."); + let big_addr: u64 = 9 * 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rb b/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..77ec2d417 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => { + info!("Error mapping kernel binary: {}", string); + cpu::qemu_exit_failure() + } + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + info!("Enabling MMU failed: {}", e); + cpu::qemu_exit_failure() + } + + memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs new file mode 100644 index 000000000..ac7c8ae4b --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception, memory}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/boot_test_string.rb b/14_virtual_mem_part2_mmio_remap/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_exit_success/mod.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_wait_forever/mod.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/14_virtual_mem_part2_mmio_remap/libraries/test-macros/Cargo.toml b/14_virtual_mem_part2_mmio_remap/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/14_virtual_mem_part2_mmio_remap/libraries/test-macros/src/lib.rs b/14_virtual_mem_part2_mmio_remap/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/14_virtual_mem_part2_mmio_remap/libraries/test-types/Cargo.toml b/14_virtual_mem_part2_mmio_remap/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/14_virtual_mem_part2_mmio_remap/libraries/test-types/src/lib.rs b/14_virtual_mem_part2_mmio_remap/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/14_virtual_mem_part2_mmio_remap/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/15_virtual_mem_part2_mmio_remap/.vscode/settings.json b/15_virtual_mem_part2_mmio_remap/.vscode/settings.json deleted file mode 100644 index a0d6a9202..000000000 --- a/15_virtual_mem_part2_mmio_remap/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] -} diff --git a/15_virtual_mem_part2_mmio_remap/Cargo.lock b/15_virtual_mem_part2_mmio_remap/Cargo.lock deleted file mode 100644 index 8930bc96d..000000000 --- a/15_virtual_mem_part2_mmio_remap/Cargo.lock +++ /dev/null @@ -1,91 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626fdbb0f6fa1e6be6df0e94795998894c4ad08d3221e12209a6c0b4f546a0c4" -dependencies = [ - "register", -] - -[[package]] -name = "kernel" -version = "0.1.0" -dependencies = [ - "cortex-a", - "qemu-exit", - "register", - "test-macros", - "test-types", -] - -[[package]] -name = "proc-macro2" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "qemu-exit" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73ae13954572c7ca0ec48ba9fe6a59c0392066eba62f8cb384ffd5addf538c5" - -[[package]] -name = "quote" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "register" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185fff3cbc031a1d17b86a980f8014002da35f9187cf4370728e0eb1eeff6829" -dependencies = [ - "tock-registers", -] - -[[package]] -name = "syn" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "443b4178719c5a851e1bde36ce12da21d74a0e60b4d982ec3385a933c812f0f6" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "test-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "test-types", -] - -[[package]] -name = "test-types" -version = "0.1.0" - -[[package]] -name = "tock-registers" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f521a79accce68c417c9c77ce22108056b626126da1932f7e2e9b5bbffee0cea" - -[[package]] -name = "unicode-xid" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" diff --git a/15_virtual_mem_part2_mmio_remap/Cargo.toml b/15_virtual_mem_part2_mmio_remap/Cargo.toml deleted file mode 100644 index 5d57cf357..000000000 --- a/15_virtual_mem_part2_mmio_remap/Cargo.toml +++ /dev/null @@ -1,55 +0,0 @@ -[package] -name = "kernel" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[profile.release] -lto = true - -# The features section is used to select the target board. -[features] -default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] -qemu-exit = "1.x.x" -test-types = { path = "test-types" } - -# Optional dependencies -register = { version = "1.x.x", features = ["no_std_unit_tests"], optional = true } - -# Platform specific dependencies -[target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "5.x.x" } - -##-------------------------------------------------------------------------------------------------- -## Testing -##-------------------------------------------------------------------------------------------------- - -[dev-dependencies] -test-macros = { path = "test-macros" } - -# Unit tests are done in the library part of the kernel. -[lib] -name = "libkernel" -test = true - -# Disable unit tests for the kernel binary. -[[bin]] -name = "kernel" -test = false - -# List of tests without harness. -[[test]] -name = "00_console_sanity" -harness = false - -[[test]] -name = "02_exception_sync_page_fault" -harness = false diff --git a/15_virtual_mem_part2_mmio_remap/Makefile b/15_virtual_mem_part2_mmio_remap/Makefile deleted file mode 100644 index 58361af8a..000000000 --- a/15_virtual_mem_part2_mmio_remap/Makefile +++ /dev/null @@ -1,177 +0,0 @@ -## SPDX-License-Identifier: MIT OR Apache-2.0 -## -## Copyright (c) 2018-2020 Andre Richter - -# Default to the RPi3 -BSP ?= rpi3 - -# Default to a serial device name that is common in Linux. -DEV_SERIAL ?= /dev/ttyUSB0 - -# Query the host system's kernel name -UNAME_S = $(shell uname -s) - -# BSP-specific arguments -ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg - JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img - LINKER_FILE = src/bsp/raspberrypi/link.ld - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -endif - -# Export for build.rs -export LINKER_FILE - -# Testing-specific arguments -ifdef TEST - ifeq ($(TEST),unit) - TEST_ARG = --lib - else - TEST_ARG = --test $(TEST) - endif -endif - -QEMU_MISSING_STRING = "This board is not yet supported for QEMU." - -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs - -FEATURES = bsp_$(BSP) -COMPILER_ARGS = --target=$(TARGET) \ - --features $(FEATURES) \ - --release - -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -DOC_CMD = cargo doc $(COMPILER_ARGS) -CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -TEST_CMD = cargo test $(COMPILER_ARGS) -OBJCOPY_CMD = rust-objcopy \ - --strip-all \ - -O binary - -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot -DOCKER_ARG_DEV = --privileged -v /dev:/dev -DOCKER_ARG_NET = --network host - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) - DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) - DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) - DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) -else - DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# -endif - -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb - -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu test chainboot jtagboot openocd gdb gdb-opt0 \ - clippy clean readelf objdump nm check - -all: $(KERNEL_BIN) - -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) - -$(KERNEL_BIN): $(KERNEL_ELF) - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - -doc: - $(DOC_CMD) --document-private-items --open - -ifeq ($(QEMU_MACHINE_TYPE),) -qemu test: - @echo $(QEMU_MISSING_STRING) -else -qemu: $(KERNEL_BIN) - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) - -define KERNEL_TEST_RUNNER - #!/usr/bin/env bash - - $(OBJCOPY_CMD) $$1 $$1.img - TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') - $(DOCKER_TEST) ruby tests/runner.rb $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY -endef - -export KERNEL_TEST_RUNNER -test: - @mkdir -p target - @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh - @chmod +x target/kernel_test_runner.sh - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) -endif - -chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) - -jtagboot: - @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) - -openocd: - @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) - -define gen_gdb - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC) $1" $(RUSTC_CMD) - @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) -endef - -gdb: - $(call gen_gdb,-C debuginfo=2) - -gdb-opt0: - $(call gen_gdb,-C debuginfo=2 -C opt-level=0) - -clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) - -clean: - rm -rf target $(KERNEL_BIN) - -readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) - -objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - -nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt - -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json diff --git a/15_virtual_mem_part2_mmio_remap/README.md b/15_virtual_mem_part2_mmio_remap/README.md deleted file mode 100644 index 44a9eebd7..000000000 --- a/15_virtual_mem_part2_mmio_remap/README.md +++ /dev/null @@ -1,3052 +0,0 @@ -# Tutorial 15 - Virtual Memory Part 2: MMIO Remap - -## tl;dr - -- We introduce a first set of changes which we eventually need for separating `kernel` and `user` - address spaces. -- The memory mapping strategy gets more sophisticated as we do away with `identity mapping` the - whole of the board's address space. -- Instead, only ranges that are actually needed are mapped: - - The `kernel binary` stays `identity mapped` for now. - - Device `MMIO regions` are remapped lazily to a special virtual address region at the top of - the virtual address space during the device driver's `init()`. - -## Table of Contents - -- [Introduction](#introduction) -- [Implementation](#implementation) - - [A New Mapping API in `src/memory/mmu.rs`](#a-new-mapping-api-in-srcmemorymmurs) - - [Using the new API in `bsp` code and drivers](#using-the-new-api-in-bsp-code-and-drivers) - - [Additional Changes](#additional-changes) -- [Test it](#test-it) -- [Diff to previous](#diff-to-previous) - -## Introduction - -This tutorial is a first step of many needed for enabling `userspace applications` (which we -hopefully will have some day in the very distant future). - -For this, one of the features we want is a clean separation of `kernel` and `user` address spaces. -Fortunately, `ARMv8` has convenient architecture support to realize this. The following text and -pictue gives some more motivation and technical information. It is quoted from the _[ARM Cortex-A -Series Programmer’s Guide for ARMv8-A], Chapter 12.2, Separation of kernel and application Virtual -Address spaces_: - -> Operating systems typically have a number of applications or tasks running concurrently. Each of -> these has its own unique set of translation tables and the kernel switches from one to another as -> part of the process of switching context between one task and another. However, much of the memory -> system is used only by the kernel and has fixed virtual to Physical Address mappings where the -> translation table entries rarely change. The ARMv8 architecture provides a number of features to -> efficiently handle this requirement. -> -> The table base addresses are specified in the Translation Table Base Registers `TTBR0_EL1` and -> `TTBR1_EL1`. The translation table pointed to by `TTBR0` is selected when the upper bits of the VA -> are all 0. `TTBR1` is selected when the upper bits of the VA are all set to 1. [...] -> -> Figure 12-4 shows how the kernel space can be mapped to the most significant area of memory and -> the Virtual Address space associated with each application mapped to the least significant area of -> memory. However, both of these are mapped to a much smaller Physical Address space. - -

- -

- -This approach is also sometimes called a "[higher half kernel]". To eventually achieve this -separation, this tutorial makes a start by changing the following things: - -1. Instead of bulk-`identity mapping` the whole of the board's address space, only the particular - parts that are needed will be mapped. -1. For now, the `kernel binary` stays identity mapped. This will be changed in the next tutorial as - it is a quite difficult and peculiar exercise to remap the kernel. -1. Device `MMIO regions` are lazily remapped during the device driver's `init()`. - 1. The remappings will populate the top of the virtual address space. In the `AArch64 MMU - Driver`, we provide the top `256 MiB` for it. - 1. It is possible to define the size of the virtual address space at compile time. We chose `8 - GiB` for now, which means remapped MMIO virtual addresses will start at `7936 MiB` - (`0x1F0000000`). -1. We keep using `TTBR0` for the kernel page tables for now. This will be changed when we remap the - `kernel binary` in the next tutorial. - -[ARM Cortex-A Series Programmer’s Guide for ARMv8-A]: https://developer.arm.com/documentation/den0024/latest/ -[higher half kernel]: https://wiki.osdev.org/Higher_Half_Kernel - -## Implementation - -Until now, the whole address space of the board was identity mapped at once. The **architecture** -(`src/_arch/_/memory/**`) and **bsp** (`src/bsp/_/memory/**`) parts of the kernel worked -together directly while setting up the translation tables, without any indirection through **generic -kernel code** (`src/memory/**`). - -The way it worked was that the `architectural MMU driver` would query the `bsp code` about the start -and end of the physical address space, and any special regions in this space that need a mapping -that _is not_ normal chacheable DRAM. It would then go ahead and map the whole address space at once -and never touch the page tables again during runtime. - -Changing in this tutorial, **architecture** and **bsp** code will no longer talk to each other -directly. Instead, this is decoupled now through the kernel's **generic MMU subsystem code**. - -### A New Mapping API in `src/memory/mmu.rs` - -First, we define an interface for operating on `translation tables`: - -```rust -/// Translation table operations. -pub trait TranslationTable { - /// Anything that needs to run before any of the other provided functions can be used. - unsafe fn init(&mut self); - - /// The translation table's base address to be used for programming the MMU. - fn phys_base_address(&self) -> Address; - - /// Map the given physical pages to the given virtual pages. - unsafe fn map_pages_at( - &mut self, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, - ) -> Result<(), &'static str>; - - /// Obtain a free virtual page slice in the MMIO region. - /// - /// The "MMIO region" is a distinct region of the implementor's choice, which allows - /// differentiating MMIO addresses from others. This can speed up debugging efforts. - /// Ideally, those MMIO addresses are also standing out visually so that a human eye can - /// identify them. For example, by allocating them from near the end of the virtual address - /// space. - fn next_mmio_virt_page_slice( - &mut self, - num_pages: usize, - ) -> Result, &'static str>; - - /// Check if a virtual page splice is in the "MMIO region". - fn is_virt_page_slice_mmio(&self, virt_pages: &PageSliceDescriptor) -> bool; -} -``` - -The MMU driver (`src/_arch/_/memory/mmu.rs`) has one global instance for the kernel tables which -implements this interface, and which can be accessed by calling -`arch_mmu::kernel_translation_tables()` in the generic kernel code (`src/memory/mmu.rs`). From -there, we provice a couple of memory mapping functions that wrap around this interface , and which -are exported for the rest of the kernel to use: - -```rust -/// Raw mapping of virtual to physical pages in the kernel translation tables. -/// -/// Prevents mapping into the MMIO range of the tables. -pub unsafe fn kernel_map_pages_at( - name: &'static str, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, -) -> Result<(), &'static str>; - -/// MMIO remapping in the kernel translation tables. -/// -/// Typically used by device drivers. -pub unsafe fn kernel_map_mmio( - name: &'static str, - phys_mmio_descriptor: &MMIODescriptor, -) -> Result, &'static str>; - -/// Map the kernel's binary and enable the MMU. -pub unsafe fn kernel_map_binary_and_enable_mmu() -> Result<(), &'static str> ; -``` - -### Using the new API in `bsp` code and drivers - -For now, there are two places where the new API is used. First, in `src/bsp/_/memory/mmu.rs`, which -provides a dedicated call to **map the kernel binary** (because it is the `BSP` that provides the -`linker script`, which in turn defines the final layout of the kernel in memory): - -```rust -/// Map the kernel binary. -pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { - kernel_mmu::kernel_map_pages_at( - "Kernel boot-core stack", - &phys_stack_page_desc(), - &virt_stack_page_desc(), - &AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - )?; - - kernel_mmu::kernel_map_pages_at( - "Kernel code and RO data", - // omitted for brevity. - )?; - - kernel_mmu::kernel_map_pages_at( - "Kernel data and bss", - // omitted for brevity. - )?; - - Ok(()) -} -``` - -Second, in device drivers, which now expect an `MMIODescriptor` type instead of a raw address. The -following is an example for the `UART`: - -```rust -impl PL011Uart { - /// Create an instance. - pub const unsafe fn new( - phys_mmio_descriptor: memory::mmu::MMIODescriptor, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { - Self { - // omitted for brevity. - } - } -} -``` - -When the kernel calls the driver's implementation of `driver::interface::DeviceDriver::init()` -during kernel boot, the MMIO Descriptor is used to remap the MMIO region on demand: - -```rust -unsafe fn init(&self) -> Result<(), &'static str> { - let virt_addr = - memory::mmu::kernel_map_mmio(self.compatible(), &self.phys_mmio_descriptor)?; - - self.inner.lock(|inner| inner.init(Some(virt_addr.into_usize())))?; - - // omitted for brevity. - - Ok(()) -} -``` - -### Supporting Changes - -There's a couple of changes not covered in this tutorial text, but the reader should ideally skim -through them: - -- [`src/memory/mmu/types.rs`](src/memory/mmu/types.rs) introduces a couple of supporting types, like - `Address`, which is used to differentiate between `Physical` and `Virtual` addresses. -- [`src/memory/mmu/mapping_record.rs`](src/memory/mmu/mapping_record.rs) provides the generic kernel - code's way of tracking previous memory mappings for use cases such as reusing existing mappings - (in case of drivers that have their MMIO ranges in the same `64 KiB` page) or printing mappings - statistics. - -## Test it - -When you load the kernel, you can now see that the driver's MMIO virtual addresses start at -`0x1F0000000`: - -Raspberry Pi 3: - -```console -$ make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 3 - -[ML] Requesting binary -[MP] ⏩ Pushing 67 KiB ========================================🦀 100% 33 KiB/s Time: 00:00:02 -[ML] Loaded! Executing the payload now - -[ 3.041355] Booting on: Raspberry Pi 3 -[ 3.042438] MMU online: -[ 3.043609] ----------------------------------------------------------------------------------------------------------------- -[ 3.049466] Virtual Physical Size Attr Entity -[ 3.055323] ----------------------------------------------------------------------------------------------------------------- -[ 3.061183] 0x000070000..0x00007FFFF --> 0x000070000..0x00007FFFF | 64 KiB | C RW XN | Kernel boot-core stack -[ 3.066476] 0x000080000..0x00008FFFF --> 0x000080000..0x00008FFFF | 64 KiB | C RO X | Kernel code and RO data -[ 3.071812] 0x000090000..0x0001AFFFF --> 0x000090000..0x0001AFFFF | 1 MiB | C RW XN | Kernel data and bss -[ 3.076975] 0x1F0000000..0x1F000FFFF --> 0x03F200000..0x03F20FFFF | 64 KiB | Dev RW XN | BCM GPIO -[ 3.081658] | BCM PL011 UART -[ 3.086606] 0x1F0010000..0x1F001FFFF --> 0x03F000000..0x03F00FFFF | 64 KiB | Dev RW XN | BCM Peripheral Interrupt Controller -[ 3.092462] ----------------------------------------------------------------------------------------------------------------- -``` - -Raspberry Pi 4: - -```console -$ BSP=rpi4 make chainboot -[...] -Minipush 1.0 - -[MP] ⏳ Waiting for /dev/ttyUSB0 -[MP] ✅ Connected - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| - - Raspberry Pi 4 - -[ML] Requesting binary -[MP] ⏩ Pushing 74 KiB ========================================🦀 100% 24 KiB/s Time: 00:00:03 -[ML] Loaded! Executing the payload now - -[ 3.376642] Booting on: Raspberry Pi 4 -[ 3.377030] MMU online: -[ 3.378202] ----------------------------------------------------------------------------------------------------------------- -[ 3.384059] Virtual Physical Size Attr Entity -[ 3.389916] ----------------------------------------------------------------------------------------------------------------- -[ 3.395775] 0x000070000..0x00007FFFF --> 0x000070000..0x00007FFFF | 64 KiB | C RW XN | Kernel boot-core stack -[ 3.401069] 0x000080000..0x00008FFFF --> 0x000080000..0x00008FFFF | 64 KiB | C RO X | Kernel code and RO data -[ 3.406404] 0x000090000..0x0001AFFFF --> 0x000090000..0x0001AFFFF | 1 MiB | C RW XN | Kernel data and bss -[ 3.411566] 0x1F0000000..0x1F000FFFF --> 0x0FE200000..0x0FE20FFFF | 64 KiB | Dev RW XN | BCM GPIO -[ 3.416251] | BCM PL011 UART -[ 3.421198] 0x1F0010000..0x1F001FFFF --> 0x0FF840000..0x0FF84FFFF | 64 KiB | Dev RW XN | GICD -[ 3.425709] | GICC -[ 3.430221] ----------------------------------------------------------------------------------------------------------------- -``` - -## Diff to previous -```diff - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu.rs 15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu.rs ---- 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu.rs -+++ 15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu.rs -@@ -68,7 +68,7 @@ - ELR_EL2.set(runtime_init::runtime_init as *const () as u64); - - // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. -- SP_EL1.set(bsp::memory::boot_core_stack_end() as u64); -+ SP_EL1.set(bsp::memory::phys_boot_core_stack_end().into_usize() as u64); - - // Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. - asm::eret() - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs 15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs ---- 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs -+++ 15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs -@@ -4,10 +4,19 @@ - - //! Memory Management Unit Driver. - //! --//! Static translation tables, compiled on boot; Everything 64 KiB granule. -+//! Only 64 KiB granule is supported. - --use super::{AccessPermissions, AttributeFields, MemAttributes}; --use crate::{bsp, memory}; -+use crate::{ -+ bsp, -+ memory::{ -+ mmu, -+ mmu::{ -+ AccessPermissions, Address, AddressType, AttributeFields, MemAttributes, Page, -+ PageSliceDescriptor, Physical, Virtual, -+ }, -+ }, -+ synchronization::InitStateLock, -+}; - use core::convert; - use cortex_a::{barrier, regs::*}; - use register::{register_bitfields, InMemoryRegister}; -@@ -15,6 +24,7 @@ - //-------------------------------------------------------------------------------------------------- - // Private Definitions - //-------------------------------------------------------------------------------------------------- -+use mmu::interface::TranslationGranule; - - // A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. - register_bitfields! {u64, -@@ -81,9 +91,6 @@ - ] - } - --const SIXTYFOUR_KIB_SHIFT: usize = 16; // log2(64 * 1024) --const FIVETWELVE_MIB_SHIFT: usize = 29; // log2(512 * 1024 * 1024) -- - /// A table descriptor for 64 KiB aperture. - /// - /// The output points to the next table. -@@ -98,36 +105,65 @@ - #[repr(transparent)] - struct PageDescriptor(u64); - -+#[derive(Copy, Clone)] -+enum Granule512MiB {} -+ -+trait BaseAddr { -+ fn phys_base_addr(&self) -> Address; -+} -+ -+/// Constants for indexing the MAIR_EL1. -+#[allow(dead_code)] -+mod mair { -+ pub const DEVICE: u64 = 0; -+ pub const NORMAL: u64 = 1; -+} -+ -+/// Memory Management Unit type. -+struct MemoryManagementUnit; -+ -+/// This constant is the power-of-two exponent that defines the virtual address space size. -+/// -+/// Values tested and known to be working: -+/// - 30 (1 GiB) -+/// - 31 (2 GiB) -+/// - 32 (4 GiB) -+/// - 33 (8 GiB) -+const ADDR_SPACE_SIZE_EXPONENT: usize = 33; -+ -+const NUM_LVL2_TABLES: usize = (1 << ADDR_SPACE_SIZE_EXPONENT) >> Granule512MiB::SHIFT; -+const T0SZ: u64 = (64 - ADDR_SPACE_SIZE_EXPONENT) as u64; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ - /// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB - /// aligned, hence the "reverse" order of appearance. - #[repr(C)] - #[repr(align(65536))] --struct FixedSizeTranslationTable { -+pub(in crate::memory::mmu) struct FixedSizeTranslationTable { - /// Page descriptors, covering 64 KiB windows per entry. - lvl3: [[PageDescriptor; 8192]; NUM_TABLES], - - /// Table descriptors, covering 512 MiB windows. - lvl2: [TableDescriptor; NUM_TABLES], --} - --/// Usually evaluates to 1 GiB for RPi3 and 4 GiB for RPi 4. --const NUM_LVL2_TABLES: usize = bsp::memory::mmu::addr_space_size() >> FIVETWELVE_MIB_SHIFT; --type ArchTranslationTable = FixedSizeTranslationTable; -+ /// Index of the next free MMIO page. -+ cur_l3_mmio_index: usize, - --trait BaseAddr { -- fn base_addr_u64(&self) -> u64; -- fn base_addr_usize(&self) -> usize; -+ /// Have the tables been initialized? -+ initialized: bool, - } - --/// Constants for indexing the MAIR_EL1. --#[allow(dead_code)] --mod mair { -- pub const DEVICE: u64 = 0; -- pub const NORMAL: u64 = 1; --} -+pub(in crate::memory::mmu) type ArchTranslationTable = FixedSizeTranslationTable; - --/// Memory Management Unit type. --struct MemoryManagementUnit; -+// Supported translation granules are exported below, so that BSP code can pick between the options. -+// This driver only supports 64 KiB at the moment. -+ -+#[derive(Copy, Clone)] -+/// 64 KiB translation granule. -+pub enum Granule64KiB {} - - //-------------------------------------------------------------------------------------------------- - // Global instances -@@ -138,7 +174,8 @@ - /// # Safety - /// - /// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". --static mut KERNEL_TABLES: ArchTranslationTable = ArchTranslationTable::new(); -+static KERNEL_TABLES: InitStateLock = -+ InitStateLock::new(ArchTranslationTable::new()); - - static MMU: MemoryManagementUnit = MemoryManagementUnit; - -@@ -146,13 +183,15 @@ - // Private Code - //-------------------------------------------------------------------------------------------------- - --impl BaseAddr for [T; N] { -- fn base_addr_u64(&self) -> u64 { -- self as *const T as u64 -- } -+impl mmu::interface::TranslationGranule for Granule512MiB { -+ const SIZE: usize = 512 * 1024 * 1024; -+ const SHIFT: usize = 29; // log2(SIZE) -+} - -- fn base_addr_usize(&self) -> usize { -- self as *const _ as usize -+impl BaseAddr for [T; N] { -+ fn phys_base_addr(&self) -> Address { -+ // The binary is still identity mapped, so we don't need to convert here. -+ Address::new(self as *const _ as usize) - } - } - -@@ -160,7 +199,7 @@ - fn from(next_lvl_table_addr: usize) -> Self { - let val = InMemoryRegister::::new(0); - -- let shifted = next_lvl_table_addr >> SIXTYFOUR_KIB_SHIFT; -+ let shifted = next_lvl_table_addr >> Granule64KiB::SHIFT; - val.write( - STAGE1_TABLE_DESCRIPTOR::VALID::True - + STAGE1_TABLE_DESCRIPTOR::TYPE::Table -@@ -207,23 +246,33 @@ - - impl PageDescriptor { - /// Create an instance. -- fn new(output_addr: usize, attribute_fields: AttributeFields) -> Self { -+ fn new(output_addr: *const Page, attribute_fields: &AttributeFields) -> Self { - let val = InMemoryRegister::::new(0); - -- let shifted = output_addr as u64 >> SIXTYFOUR_KIB_SHIFT; -+ let shifted = output_addr as u64 >> Granule64KiB::SHIFT; - val.write( - STAGE1_PAGE_DESCRIPTOR::VALID::True - + STAGE1_PAGE_DESCRIPTOR::AF::True -- + attribute_fields.into() -+ + attribute_fields.clone().into() - + STAGE1_PAGE_DESCRIPTOR::TYPE::Table - + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted), - ); - - Self(val.get()) - } -+ -+ /// Returns the valid bit. -+ fn is_valid(&self) -> bool { -+ InMemoryRegister::::new(self.0) -+ .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) -+ } - } - - impl FixedSizeTranslationTable<{ NUM_TABLES }> { -+ // Reserve the last 256 MiB of the address space for MMIO mappings. -+ const L2_MMIO_START_INDEX: usize = NUM_TABLES - 1; -+ const L3_MMIO_START_INDEX: usize = 8192 / 2; -+ - /// Create an instance. - pub const fn new() -> Self { - assert!(NUM_TABLES > 0); -@@ -231,7 +280,55 @@ - Self { - lvl3: [[PageDescriptor(0); 8192]; NUM_TABLES], - lvl2: [TableDescriptor(0); NUM_TABLES], -+ cur_l3_mmio_index: 0, -+ initialized: false, -+ } -+ } -+ -+ /// The start address of the table's MMIO range. -+ #[inline(always)] -+ fn mmio_start_addr(&self) -> Address { -+ Address::new( -+ (Self::L2_MMIO_START_INDEX << Granule512MiB::SHIFT) -+ | (Self::L3_MMIO_START_INDEX << Granule64KiB::SHIFT), -+ ) -+ } -+ -+ /// The inclusive end address of the table's MMIO range. -+ #[inline(always)] -+ fn mmio_end_addr_inclusive(&self) -> Address { -+ Address::new( -+ (Self::L2_MMIO_START_INDEX << Granule512MiB::SHIFT) -+ | (8191 << Granule64KiB::SHIFT) -+ | (Granule64KiB::SIZE - 1), -+ ) -+ } -+ -+ /// Helper to calculate the lvl2 and lvl3 indices from an address. -+ #[inline(always)] -+ fn lvl2_lvl3_index_from( -+ &self, -+ addr: *const Page, -+ ) -> Result<(usize, usize), &'static str> { -+ let lvl2_index = addr as usize >> Granule512MiB::SHIFT; -+ let lvl3_index = (addr as usize & Granule512MiB::MASK) >> Granule64KiB::SHIFT; -+ -+ if lvl2_index > (NUM_TABLES - 1) { -+ return Err("Virtual page is out of bounds of translation table"); - } -+ -+ Ok((lvl2_index, lvl3_index)) -+ } -+ -+ /// Returns the PageDescriptor corresponding to the supplied Page. -+ #[inline(always)] -+ fn page_descriptor_from( -+ &mut self, -+ addr: *const Page, -+ ) -> Result<&mut PageDescriptor, &'static str> { -+ let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from(addr)?; -+ -+ Ok(&mut self.lvl3[lvl2_index][lvl3_index]) - } - } - -@@ -248,28 +345,6 @@ - ); - } - --/// Iterates over all static translation table entries and fills them at once. --/// --/// # Safety --/// --/// - Modifies a `static mut`. Ensure it only happens from here. --unsafe fn populate_tt_entries() -> Result<(), &'static str> { -- for (l2_nr, l2_entry) in KERNEL_TABLES.lvl2.iter_mut().enumerate() { -- *l2_entry = KERNEL_TABLES.lvl3[l2_nr].base_addr_usize().into(); -- -- for (l3_nr, l3_entry) in KERNEL_TABLES.lvl3[l2_nr].iter_mut().enumerate() { -- let virt_addr = (l2_nr << FIVETWELVE_MIB_SHIFT) + (l3_nr << SIXTYFOUR_KIB_SHIFT); -- -- let (output_addr, attribute_fields) = -- bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; -- -- *l3_entry = PageDescriptor::new(output_addr, attribute_fields); -- } -- } -- -- Ok(()) --} -- - /// Configure various settings of stage 1 of the EL1 translation regime. - fn configure_translation_control() { - let ips = ID_AA64MMFR0_EL1.read(ID_AA64MMFR0_EL1::PARange); -@@ -282,7 +357,7 @@ - + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::EPD0::EnableTTBR0Walks -- + TCR_EL1::T0SZ.val(32), // TTBR0 spans 4 GiB total. -+ + TCR_EL1::T0SZ.val(T0SZ), - ); - } - -@@ -290,17 +365,126 @@ - // Public Code - //-------------------------------------------------------------------------------------------------- - -+/// Return a guarded reference to the kernel's translation tables. -+pub(in crate::memory::mmu) fn kernel_translation_tables( -+) -> &'static InitStateLock { -+ &KERNEL_TABLES -+} -+ - /// Return a reference to the MMU instance. --pub fn mmu() -> &'static impl memory::mmu::interface::MMU { -+pub(in crate::memory::mmu) fn mmu() -> &'static impl mmu::interface::MMU { - &MMU - } - - //------------------------------------------------------------------------------ - // OS Interface Code - //------------------------------------------------------------------------------ -+impl mmu::interface::TranslationGranule for Granule64KiB { -+ const SIZE: usize = 64 * 1024; -+ const SHIFT: usize = 16; // log2(SIZE) -+} -+ -+impl mmu::interface::TranslationTable -+ for FixedSizeTranslationTable<{ NUM_TABLES }> -+{ -+ unsafe fn init(&mut self) { -+ if self.initialized { -+ return; -+ } -+ -+ // Populate the l2 entries. -+ for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { -+ *lvl2_entry = self.lvl3[lvl2_nr].phys_base_addr().into_usize().into(); -+ } -+ -+ self.cur_l3_mmio_index = Self::L3_MMIO_START_INDEX; -+ self.initialized = true; -+ } -+ -+ fn phys_base_address(&self) -> Address { -+ self.lvl2.phys_base_addr() -+ } -+ -+ unsafe fn map_pages_at( -+ &mut self, -+ phys_pages: &PageSliceDescriptor, -+ virt_pages: &PageSliceDescriptor, -+ attr: &AttributeFields, -+ ) -> Result<(), &'static str> { -+ assert_eq!(self.initialized, true, "Translation tables not initialized"); -+ -+ let p = phys_pages.as_slice(); -+ let v = virt_pages.as_slice(); -+ -+ if p.len() != v.len() { -+ return Err("Tried to map page slices with unequal sizes"); -+ } - --impl memory::mmu::interface::MMU for MemoryManagementUnit { -- unsafe fn init(&self) -> Result<(), &'static str> { -+ // No work to do for empty slices. -+ if p.is_empty() { -+ return Ok(()); -+ } -+ -+ if p.last().unwrap().as_ptr() >= bsp::memory::mmu::phys_addr_space_end_page() { -+ return Err("Tried to map outside of physical address space"); -+ } -+ -+ let iter = p.iter().zip(v.iter()); -+ for (phys_page, virt_page) in iter { -+ let page_descriptor = self.page_descriptor_from(virt_page.as_ptr())?; -+ if page_descriptor.is_valid() { -+ return Err("Virtual page is already mapped"); -+ } -+ -+ *page_descriptor = PageDescriptor::new(phys_page.as_ptr(), &attr); -+ } -+ -+ Ok(()) -+ } -+ -+ fn next_mmio_virt_page_slice( -+ &mut self, -+ num_pages: usize, -+ ) -> Result, &'static str> { -+ assert_eq!(self.initialized, true, "Translation tables not initialized"); -+ -+ if num_pages == 0 { -+ return Err("num_pages == 0"); -+ } -+ -+ if (self.cur_l3_mmio_index + num_pages) > 8191 { -+ return Err("Not enough MMIO space left"); -+ } -+ -+ let addr = (Self::L2_MMIO_START_INDEX << Granule512MiB::SHIFT) -+ | (self.cur_l3_mmio_index << Granule64KiB::SHIFT); -+ self.cur_l3_mmio_index += num_pages; -+ -+ Ok(PageSliceDescriptor::from_addr( -+ Address::new(addr), -+ num_pages, -+ )) -+ } -+ -+ fn is_virt_page_slice_mmio(&self, virt_pages: &PageSliceDescriptor) -> bool { -+ let start_addr = virt_pages.start_addr(); -+ let end_addr_inclusive = virt_pages.end_addr_inclusive(); -+ -+ for i in [start_addr, end_addr_inclusive].iter() { -+ if (*i >= self.mmio_start_addr()) && (*i <= self.mmio_end_addr_inclusive()) { -+ return true; -+ } -+ } -+ -+ false -+ } -+} -+ -+impl mmu::interface::MMU for MemoryManagementUnit { -+ unsafe fn enable( -+ &self, -+ phys_kernel_table_base_addr: Address, -+ ) -> Result<(), &'static str> { - // Fail early if translation granule is not supported. Both RPis support it, though. - if !ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported) { - return Err("Translation granule not supported in HW"); -@@ -309,11 +493,8 @@ - // Prepare the memory attribute indirection register. - set_up_mair(); - -- // Populate translation tables. -- populate_tt_entries()?; -- - // Set the "Translation Table Base Register". -- TTBR0_EL1.set_baddr(KERNEL_TABLES.lvl2.base_addr_u64()); -+ TTBR0_EL1.set_baddr(phys_kernel_table_base_addr.into_usize() as u64); - - configure_translation_control(); - -@@ -337,6 +518,9 @@ - //-------------------------------------------------------------------------------------------------- - - #[cfg(test)] -+pub(in crate::memory::mmu) type MinSizeArchTranslationTable = FixedSizeTranslationTable<1>; -+ -+#[cfg(test)] - mod tests { - use super::*; - use test_macros::kernel_test; -@@ -363,7 +547,7 @@ - #[kernel_test] - fn kernel_tables_in_bss() { - let bss_range = bsp::memory::bss_range_inclusive(); -- let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; -+ let kernel_tables_addr = &KERNEL_TABLES as *const _ as usize as *mut u64; - - assert!(bss_range.contains(&kernel_tables_addr)); - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/time.rs 15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs ---- 14_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/time.rs -+++ 15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs -@@ -55,7 +55,7 @@ - } - - // Calculate the register compare value. -- let frq = CNTFRQ_EL0.get() as u64; -+ let frq = CNTFRQ_EL0.get(); - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs -@@ -4,7 +4,9 @@ - - //! GICC Driver - GIC CPU interface. - --use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; -+use crate::{ -+ bsp::device_driver::common::MMIODerefWrapper, exception, synchronization::InitStateLock, -+}; - use register::{mmio::*, register_bitfields, register_structs}; - - //-------------------------------------------------------------------------------------------------- -@@ -56,12 +58,13 @@ - - /// Representation of the GIC CPU interface. - pub struct GICC { -- registers: Registers, -+ registers: InitStateLock, - } - - //-------------------------------------------------------------------------------------------------- - // Public Code - //-------------------------------------------------------------------------------------------------- -+use crate::synchronization::interface::ReadWriteEx; - - impl GICC { - /// Create an instance. -@@ -71,10 +74,15 @@ - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { -- registers: Registers::new(mmio_start_addr), -+ registers: InitStateLock::new(Registers::new(mmio_start_addr)), - } - } - -+ pub unsafe fn set_mmio(&self, new_mmio_start_addr: usize) { -+ self.registers -+ .write(|regs| *regs = Registers::new(new_mmio_start_addr)); -+ } -+ - /// Accept interrupts of any priority. - /// - /// Quoting the GICv2 Architecture Specification: -@@ -87,7 +95,9 @@ - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - pub fn priority_accept_all(&self) { -- self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. -+ self.registers.read(|regs| { -+ regs.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. -+ }); - } - - /// Enable the interface - start accepting IRQs. -@@ -97,7 +107,9 @@ - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - pub fn enable(&self) { -- self.registers.CTLR.write(CTLR::Enable::SET); -+ self.registers.read(|regs| { -+ regs.CTLR.write(CTLR::Enable::SET); -+ }); - } - - /// Extract the number of the highest-priority pending IRQ. -@@ -113,7 +125,8 @@ - &self, - _ic: &exception::asynchronous::IRQContext<'irq_context>, - ) -> usize { -- self.registers.IAR.read(IAR::InterruptID) as usize -+ self.registers -+ .read(|regs| regs.IAR.read(IAR::InterruptID) as usize) - } - - /// Complete handling of the currently active IRQ. -@@ -132,6 +145,8 @@ - irq_number: u32, - _ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { -- self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); -+ self.registers.read(|regs| { -+ regs.EOIR.write(EOIR::EOIINTID.val(irq_number)); -+ }); - } - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicd.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicd.rs -@@ -8,8 +8,9 @@ - //! - SPI - Shared Peripheral Interrupt. - - use crate::{ -- bsp::device_driver::common::MMIODerefWrapper, state, synchronization, -- synchronization::IRQSafeNullLock, -+ bsp::device_driver::common::MMIODerefWrapper, -+ state, synchronization, -+ synchronization::{IRQSafeNullLock, InitStateLock}, - }; - use register::{mmio::*, register_bitfields, register_structs}; - -@@ -79,7 +80,7 @@ - shared_registers: IRQSafeNullLock, - - /// Access to banked registers is unguarded. -- banked_registers: BankedRegisters, -+ banked_registers: InitStateLock, - } - - //-------------------------------------------------------------------------------------------------- -@@ -116,6 +117,7 @@ - //-------------------------------------------------------------------------------------------------- - // Public Code - //-------------------------------------------------------------------------------------------------- -+use crate::synchronization::interface::ReadWriteEx; - use synchronization::interface::Mutex; - - impl GICD { -@@ -127,10 +129,17 @@ - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), -- banked_registers: BankedRegisters::new(mmio_start_addr), -+ banked_registers: InitStateLock::new(BankedRegisters::new(mmio_start_addr)), - } - } - -+ pub unsafe fn set_mmio(&self, new_mmio_start_addr: usize) { -+ self.shared_registers -+ .lock(|regs| *regs = SharedRegisters::new(new_mmio_start_addr)); -+ self.banked_registers -+ .write(|regs| *regs = BankedRegisters::new(new_mmio_start_addr)); -+ } -+ - /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. - /// - /// Quoting the GICv2 Architecture Specification: -@@ -138,7 +147,8 @@ - /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that - /// corresponds only to the processor reading the register." - fn local_gic_target_mask(&self) -> u32 { -- self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) -+ self.banked_registers -+ .read(|regs| regs.ITARGETSR[0].read(ITARGETSR::Offset0)) - } - - /// Route all SPIs to the boot core and enable the distributor. -@@ -177,10 +187,10 @@ - // Check if we are handling a private or shared IRQ. - match irq_num { - // Private. -- 0..=31 => { -- let enable_reg = &self.banked_registers.ISENABLER; -+ 0..=31 => self.banked_registers.read(|regs| { -+ let enable_reg = ®s.ISENABLER; - enable_reg.set(enable_reg.get() | enable_bit); -- } -+ }), - // Shared. - _ => { - let enable_reg_index_shared = enable_reg_index - 1; - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs -@@ -79,7 +79,11 @@ - mod gicc; - mod gicd; - --use crate::{bsp, cpu, driver, exception, synchronization, synchronization::InitStateLock}; -+use crate::{ -+ bsp, cpu, driver, exception, memory, memory::mmu::Physical, synchronization, -+ synchronization::InitStateLock, -+}; -+use core::sync::atomic::{AtomicBool, Ordering}; - - //-------------------------------------------------------------------------------------------------- - // Private Definitions -@@ -96,12 +100,18 @@ - - /// Representation of the GIC. - pub struct GICv2 { -+ gicd_phys_mmio_descriptor: memory::mmu::MMIODescriptor, -+ gicc_phys_mmio_descriptor: memory::mmu::MMIODescriptor, -+ - /// The Distributor. - gicd: gicd::GICD, - - /// The CPU Interface. - gicc: gicc::GICC, - -+ /// Have the MMIO regions been remapped yet? -+ is_mmio_remapped: AtomicBool, -+ - /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. - handler_table: InitStateLock, - } -@@ -118,11 +128,17 @@ - /// - /// # Safety - /// -- /// - The user must ensure to provide a correct MMIO start address. -- pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { -+ /// - The user must ensure to provide correct MMIO descriptors. -+ pub const unsafe fn new( -+ gicd_phys_mmio_descriptor: memory::mmu::MMIODescriptor, -+ gicc_phys_mmio_descriptor: memory::mmu::MMIODescriptor, -+ ) -> Self { - Self { -- gicd: gicd::GICD::new(gicd_mmio_start_addr), -- gicc: gicc::GICC::new(gicc_mmio_start_addr), -+ gicd_phys_mmio_descriptor, -+ gicc_phys_mmio_descriptor, -+ gicd: gicd::GICD::new(gicd_phys_mmio_descriptor.start_addr().into_usize()), -+ gicc: gicc::GICC::new(gicc_phys_mmio_descriptor.start_addr().into_usize()), -+ is_mmio_remapped: AtomicBool::new(false), - handler_table: InitStateLock::new([None; Self::NUM_IRQS]), - } - } -@@ -139,6 +155,22 @@ - } - - unsafe fn init(&self) -> Result<(), &'static str> { -+ let remapped = self.is_mmio_remapped.load(Ordering::Relaxed); -+ if !remapped { -+ let mut virt_addr; -+ -+ // GICD -+ virt_addr = memory::mmu::kernel_map_mmio("GICD", &self.gicd_phys_mmio_descriptor)?; -+ self.gicd.set_mmio(virt_addr.into_usize()); -+ -+ // GICC -+ virt_addr = memory::mmu::kernel_map_mmio("GICC", &self.gicc_phys_mmio_descriptor)?; -+ self.gicc.set_mmio(virt_addr.into_usize()); -+ -+ // Conclude remapping. -+ self.is_mmio_remapped.store(true, Ordering::Relaxed); -+ } -+ - if cpu::smp::core_id::() == bsp::cpu::BOOT_CORE_ID { - self.gicd.boot_core_init(); - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -@@ -5,9 +5,10 @@ - //! GPIO Driver. - - use crate::{ -- bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, -- synchronization::IRQSafeNullLock, -+ bsp::device_driver::common::MMIODerefWrapper, driver, memory, memory::mmu::Physical, -+ synchronization, synchronization::IRQSafeNullLock, - }; -+use core::sync::atomic::{AtomicUsize, Ordering}; - use register::{mmio::*, register_bitfields, register_structs}; - - //-------------------------------------------------------------------------------------------------- -@@ -117,6 +118,8 @@ - - /// Representation of the GPIO HW. - pub struct GPIO { -+ phys_mmio_descriptor: memory::mmu::MMIODescriptor, -+ virt_mmio_start_addr: AtomicUsize, - inner: IRQSafeNullLock, - } - -@@ -136,6 +139,19 @@ - } - } - -+ /// Init code. -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub unsafe fn init(&mut self, new_mmio_start_addr: Option) -> Result<(), &'static str> { -+ if let Some(addr) = new_mmio_start_addr { -+ self.registers = Registers::new(addr); -+ } -+ -+ Ok(()) -+ } -+ - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { -@@ -190,10 +206,14 @@ - /// - /// # Safety - /// -- /// - The user must ensure to provide a correct MMIO start address. -- pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ /// - The user must ensure to provide correct MMIO descriptors. -+ pub const unsafe fn new(phys_mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { - Self { -- inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), -+ phys_mmio_descriptor, -+ virt_mmio_start_addr: AtomicUsize::new(0), -+ inner: IRQSafeNullLock::new(GPIOInner::new( -+ phys_mmio_descriptor.start_addr().into_usize(), -+ )), - } - } - -@@ -212,4 +232,27 @@ - fn compatible(&self) -> &'static str { - "BCM GPIO" - } -+ -+ unsafe fn init(&self) -> Result<(), &'static str> { -+ let virt_addr = -+ memory::mmu::kernel_map_mmio(self.compatible(), &self.phys_mmio_descriptor)?; -+ -+ self.inner -+ .lock(|inner| inner.init(Some(virt_addr.into_usize())))?; -+ -+ self.virt_mmio_start_addr -+ .store(virt_addr.into_usize(), Ordering::Relaxed); -+ -+ Ok(()) -+ } -+ -+ fn virt_mmio_start_addr(&self) -> Option { -+ let addr = self.virt_mmio_start_addr.load(Ordering::Relaxed); -+ -+ if addr == 0 { -+ return None; -+ } -+ -+ Some(addr) -+ } - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs -@@ -2,12 +2,14 @@ - // - // Copyright (c) 2020 Andre Richter - --//! Peripheral Interrupt regsler Driver. -+//! Peripheral Interrupt Controller Driver. - - use super::{InterruptController, PendingIRQs, PeripheralIRQ}; - use crate::{ - bsp::device_driver::common::MMIODerefWrapper, -- exception, synchronization, -+ driver, exception, memory, -+ memory::mmu::Physical, -+ synchronization, - synchronization::{IRQSafeNullLock, InitStateLock}, - }; - use register::{mmio::*, register_structs}; -@@ -51,11 +53,13 @@ - - /// Representation of the peripheral interrupt controller. - pub struct PeripheralIC { -+ phys_mmio_descriptor: memory::mmu::MMIODescriptor, -+ - /// Access to write registers is guarded with a lock. - wo_registers: IRQSafeNullLock, - - /// Register read access is unguarded. -- ro_registers: ReadOnlyRegisters, -+ ro_registers: InitStateLock, - - /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. - handler_table: InitStateLock, -@@ -70,21 +74,26 @@ - /// - /// # Safety - /// -- /// - The user must ensure to provide a correct MMIO start address. -- pub const unsafe fn new(mmio_start_addr: usize) -> Self { -+ /// - The user must ensure to provide correct MMIO descriptors. -+ pub const unsafe fn new(phys_mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { -+ let addr = phys_mmio_descriptor.start_addr().into_usize(); -+ - Self { -- wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), -- ro_registers: ReadOnlyRegisters::new(mmio_start_addr), -+ phys_mmio_descriptor, -+ wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(addr)), -+ ro_registers: InitStateLock::new(ReadOnlyRegisters::new(addr)), - handler_table: InitStateLock::new([None; InterruptController::NUM_PERIPHERAL_IRQS]), - } - } - - /// Query the list of pending IRQs. - fn pending_irqs(&self) -> PendingIRQs { -- let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) -- | u64::from(self.ro_registers.PENDING_1.get()); -+ self.ro_registers.read(|regs| { -+ let pending_mask: u64 = -+ (u64::from(regs.PENDING_2.get()) << 32) | u64::from(regs.PENDING_1.get()); - -- PendingIRQs::new(pending_mask) -+ PendingIRQs::new(pending_mask) -+ }) - } - } - -@@ -93,6 +102,25 @@ - //------------------------------------------------------------------------------ - use synchronization::interface::{Mutex, ReadWriteEx}; - -+impl driver::interface::DeviceDriver for PeripheralIC { -+ fn compatible(&self) -> &'static str { -+ "BCM Peripheral Interrupt Controller" -+ } -+ -+ unsafe fn init(&self) -> Result<(), &'static str> { -+ let virt_addr = -+ memory::mmu::kernel_map_mmio(self.compatible(), &self.phys_mmio_descriptor)? -+ .into_usize(); -+ -+ self.wo_registers -+ .lock(|regs| *regs = WriteOnlyRegisters::new(virt_addr)); -+ self.ro_registers -+ .write(|regs| *regs = ReadOnlyRegisters::new(virt_addr)); -+ -+ Ok(()) -+ } -+} -+ - impl exception::asynchronous::interface::IRQManager for PeripheralIC { - type IRQNumberType = PeripheralIRQ; - - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs -@@ -6,7 +6,7 @@ - - mod peripheral_ic; - --use crate::{driver, exception}; -+use crate::{driver, exception, memory, memory::mmu::Physical}; - - //-------------------------------------------------------------------------------------------------- - // Private Definitions -@@ -78,10 +78,13 @@ - /// - /// # Safety - /// -- /// - The user must ensure to provide a correct MMIO start address. -- pub const unsafe fn new(_local_mmio_start_addr: usize, periph_mmio_start_addr: usize) -> Self { -+ /// - The user must ensure to provide correct MMIO descriptors. -+ pub const unsafe fn new( -+ _phys_local_mmio_descriptor: memory::mmu::MMIODescriptor, -+ phys_periph_mmio_descriptor: memory::mmu::MMIODescriptor, -+ ) -> Self { - Self { -- periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), -+ periph: peripheral_ic::PeripheralIC::new(phys_periph_mmio_descriptor), - } - } - } -@@ -94,6 +97,10 @@ - fn compatible(&self) -> &'static str { - "BCM Interrupt Controller" - } -+ -+ unsafe fn init(&self) -> Result<(), &'static str> { -+ self.periph.init() -+ } - } - - impl exception::asynchronous::interface::IRQManager for InterruptController { - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -@@ -5,10 +5,13 @@ - //! PL011 UART driver. - - use crate::{ -- bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, -- synchronization, synchronization::IRQSafeNullLock, -+ bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, memory, -+ memory::mmu::Physical, synchronization, synchronization::IRQSafeNullLock, -+}; -+use core::{ -+ fmt, -+ sync::atomic::{AtomicUsize, Ordering}, - }; --use core::fmt; - use register::{mmio::*, register_bitfields, register_structs}; - - //-------------------------------------------------------------------------------------------------- -@@ -202,6 +205,8 @@ - - /// Representation of the UART. - pub struct PL011Uart { -+ phys_mmio_descriptor: memory::mmu::MMIODescriptor, -+ virt_mmio_start_addr: AtomicUsize, - inner: IRQSafeNullLock, - irq_number: bsp::device_driver::IRQNumber, - } -@@ -232,7 +237,15 @@ - /// approximation we can get. A 5 modulo error margin is acceptable for UART and we're now at 0,01 modulo. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). -- pub fn init(&mut self) { -+ /// -+ /// # Safety -+ /// -+ /// - The user must ensure to provide a correct MMIO start address. -+ pub unsafe fn init(&mut self, new_mmio_start_addr: Option) -> Result<(), &'static str> { -+ if let Some(addr) = new_mmio_start_addr { -+ self.registers = Registers::new(addr); -+ } -+ - // Turn it off temporarily. - self.registers.CR.set(0); - -@@ -249,6 +262,8 @@ - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); -+ -+ Ok(()) - } - - /// Send a character. -@@ -318,13 +333,18 @@ - /// - /// # Safety - /// -- /// - The user must ensure to provide a correct MMIO start address. -+ /// - The user must ensure to provide correct MMIO descriptors. -+ /// - The user must ensure to provide correct IRQ numbers. - pub const unsafe fn new( -- mmio_start_addr: usize, -+ phys_mmio_descriptor: memory::mmu::MMIODescriptor, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { - Self { -- inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), -+ phys_mmio_descriptor, -+ virt_mmio_start_addr: AtomicUsize::new(0), -+ inner: IRQSafeNullLock::new(PL011UartInner::new( -+ phys_mmio_descriptor.start_addr().into_usize(), -+ )), - irq_number, - } - } -@@ -341,7 +361,14 @@ - } - - unsafe fn init(&self) -> Result<(), &'static str> { -- self.inner.lock(|inner| inner.init()); -+ let virt_addr = -+ memory::mmu::kernel_map_mmio(self.compatible(), &self.phys_mmio_descriptor)?; -+ -+ self.inner -+ .lock(|inner| inner.init(Some(virt_addr.into_usize())))?; -+ -+ self.virt_mmio_start_addr -+ .store(virt_addr.into_usize(), Ordering::Relaxed); - - Ok(()) - } -@@ -360,6 +387,16 @@ - - Ok(()) - } -+ -+ fn virt_mmio_start_addr(&self) -> Option { -+ let addr = self.virt_mmio_start_addr.load(Ordering::Relaxed); -+ -+ if addr == 0 { -+ return None; -+ } -+ -+ Some(addr) -+ } - } - - impl console::interface::Write for PL011Uart { - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs -@@ -5,7 +5,7 @@ - //! BSP console facilities. - - use super::memory; --use crate::{bsp::device_driver, console}; -+use crate::{bsp::device_driver, console, cpu}; - use core::fmt; - - //-------------------------------------------------------------------------------------------------- -@@ -23,11 +23,25 @@ - /// - /// - Use only for printing during a panic. - pub unsafe fn panic_console_out() -> impl fmt::Write { -- let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); -- let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); -+ use crate::driver::interface::DeviceDriver; - -+ let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START.into_usize()); -+ let mut panic_uart = -+ device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.into_usize()); -+ -+ // If remapping of the driver's MMIO already happened, take the remapped start address. -+ // Otherwise, take a chance with the default physical address. -+ let maybe_gpio_mmio_start_addr = super::GPIO.virt_mmio_start_addr(); -+ let maybe_uart_mmio_start_addr = super::PL011_UART.virt_mmio_start_addr(); -+ -+ panic_gpio -+ .init(maybe_gpio_mmio_start_addr) -+ .unwrap_or_else(|_| cpu::wait_forever()); - panic_gpio.map_pl011_uart(); -- panic_uart.init(); -+ panic_uart -+ .init(maybe_uart_mmio_start_addr) -+ .unwrap_or_else(|_| cpu::wait_forever()); -+ - panic_uart - } - - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs -@@ -46,7 +46,15 @@ - &self.device_drivers[..] - } - -- fn post_device_driver_init(&self) { -+ fn early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { -+ &self.device_drivers[0..=1] -+ } -+ -+ fn non_early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { -+ &self.device_drivers[2..] -+ } -+ -+ fn post_early_print_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld -@@ -42,6 +42,11 @@ - . += 8; - __bss_end_inclusive = . - 8; - } -+ . = ALIGN(65536); -+ __data_end = .; -+ -+ __ro_size = __ro_end - __ro_start; -+ __data_size = __data_end - __ro_end; - - /DISCARD/ : { *(.comment*) } - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs -@@ -4,72 +4,128 @@ - - //! BSP Memory Management Unit. - --use super::map as memory_map; --use crate::memory::mmu::*; --use core::ops::RangeInclusive; -+use crate::{ -+ common, -+ memory::{ -+ mmu as kernel_mmu, -+ mmu::{ -+ interface, AccessPermissions, AttributeFields, Granule64KiB, MemAttributes, Page, -+ PageSliceDescriptor, Physical, Virtual, -+ }, -+ }, -+}; - - //-------------------------------------------------------------------------------------------------- - // Public Definitions - //-------------------------------------------------------------------------------------------------- - --const NUM_MEM_RANGES: usize = 2; -- --/// The virtual memory layout. --/// --/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. --/// It is agnostic of the paging granularity that the architecture's MMU will use. --pub static LAYOUT: KernelVirtualLayout<{ NUM_MEM_RANGES }> = KernelVirtualLayout::new( -- memory_map::END_INCLUSIVE, -- [ -- TranslationDescriptor { -- name: "Kernel code and RO data", -- virtual_range: ro_range_inclusive, -- physical_range_translation: Translation::Identity, -- attribute_fields: AttributeFields { -- mem_attributes: MemAttributes::CacheableDRAM, -- acc_perms: AccessPermissions::ReadOnly, -- execute_never: false, -- }, -- }, -- TranslationDescriptor { -- name: "Device MMIO", -- virtual_range: mmio_range_inclusive, -- physical_range_translation: Translation::Identity, -- attribute_fields: AttributeFields { -- mem_attributes: MemAttributes::Device, -- acc_perms: AccessPermissions::ReadWrite, -- execute_never: true, -- }, -- }, -- ], --); -+/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to -+/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. -+pub type KernelGranule = Granule64KiB; - - //-------------------------------------------------------------------------------------------------- - // Private Code - //-------------------------------------------------------------------------------------------------- -+use interface::TranslationGranule; -+ -+/// Helper function for calculating the number of pages the given parameter spans. -+const fn size_to_num_pages(size: usize) -> usize { -+ assert!(size > 0); -+ assert!(size modulo KernelGranule::SIZE == 0); -+ -+ size >> KernelGranule::SHIFT -+} -+ -+/// The boot core's stack. -+fn virt_stack_page_desc() -> PageSliceDescriptor { -+ let num_pages = size_to_num_pages(super::boot_core_stack_size()); -+ -+ PageSliceDescriptor::from_addr(super::virt_boot_core_stack_start(), num_pages) -+} -+ -+/// The Read-Only (RO) pages of the kernel binary. -+fn virt_ro_page_desc() -> PageSliceDescriptor { -+ let num_pages = size_to_num_pages(super::ro_size()); -+ -+ PageSliceDescriptor::from_addr(super::virt_ro_start(), num_pages) -+} -+ -+/// The data pages of the kernel binary. -+fn virt_data_page_desc() -> PageSliceDescriptor { -+ let num_pages = size_to_num_pages(super::data_size()); - --fn ro_range_inclusive() -> RangeInclusive { -- // Notice the subtraction to turn the exclusive end into an inclusive end. -- #[allow(clippy::range_minus_one)] -- RangeInclusive::new(super::ro_start(), super::ro_end() - 1) -+ PageSliceDescriptor::from_addr(super::virt_data_start(), num_pages) - } - --fn mmio_range_inclusive() -> RangeInclusive { -- RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) -+// The binary is still identity mapped, so we don't need to convert in the following. -+ -+/// The boot core's stack. -+fn phys_stack_page_desc() -> PageSliceDescriptor { -+ virt_stack_page_desc().into() -+} -+ -+/// The Read-Only (RO) pages of the kernel binary. -+fn phys_ro_page_desc() -> PageSliceDescriptor { -+ virt_ro_page_desc().into() -+} -+ -+/// The data pages of the kernel binary. -+fn phys_data_page_desc() -> PageSliceDescriptor { -+ virt_data_page_desc().into() - } - - //-------------------------------------------------------------------------------------------------- - // Public Code - //-------------------------------------------------------------------------------------------------- - --/// Return the address space size in bytes. --pub const fn addr_space_size() -> usize { -- memory_map::END_INCLUSIVE + 1 -+/// Pointer to the last page of the physical address space. -+pub fn phys_addr_space_end_page() -> *const Page { -+ common::align_down( -+ super::phys_addr_space_end().into_usize(), -+ KernelGranule::SIZE, -+ ) as *const Page<_> - } - --/// Return a reference to the virtual memory layout. --pub fn virt_mem_layout() -> &'static KernelVirtualLayout<{ NUM_MEM_RANGES }> { -- &LAYOUT -+/// Map the kernel binary. -+/// -+/// # Safety -+/// -+/// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking. -+pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { -+ kernel_mmu::kernel_map_pages_at( -+ "Kernel boot-core stack", -+ &phys_stack_page_desc(), -+ &virt_stack_page_desc(), -+ &AttributeFields { -+ mem_attributes: MemAttributes::CacheableDRAM, -+ acc_perms: AccessPermissions::ReadWrite, -+ execute_never: true, -+ }, -+ )?; -+ -+ kernel_mmu::kernel_map_pages_at( -+ "Kernel code and RO data", -+ &phys_ro_page_desc(), -+ &virt_ro_page_desc(), -+ &AttributeFields { -+ mem_attributes: MemAttributes::CacheableDRAM, -+ acc_perms: AccessPermissions::ReadOnly, -+ execute_never: false, -+ }, -+ )?; -+ -+ kernel_mmu::kernel_map_pages_at( -+ "Kernel data and bss", -+ &phys_data_page_desc(), -+ &virt_data_page_desc(), -+ &AttributeFields { -+ mem_attributes: MemAttributes::CacheableDRAM, -+ acc_perms: AccessPermissions::ReadWrite, -+ execute_never: true, -+ }, -+ )?; -+ -+ Ok(()) - } - - //-------------------------------------------------------------------------------------------------- -@@ -84,14 +140,12 @@ - /// Check alignment of the kernel's virtual memory layout sections. - #[kernel_test] - fn virt_mem_layout_sections_are_64KiB_aligned() { -- const SIXTYFOUR_KIB: usize = 65536; -- -- for i in LAYOUT.inner().iter() { -- let start: usize = *(i.virtual_range)().start(); -- let end: usize = *(i.virtual_range)().end() + 1; -+ for i in [virt_stack_page_desc, virt_ro_page_desc, virt_data_page_desc].iter() { -+ let start: usize = i().start_addr().into_usize(); -+ let end: usize = i().end_addr().into_usize(); - -- assert_eq!(start modulo SIXTYFOUR_KIB, 0); -- assert_eq!(end modulo SIXTYFOUR_KIB, 0); -+ assert_eq!(start modulo KernelGranule::SIZE, 0); -+ assert_eq!(end modulo KernelGranule::SIZE, 0); - assert!(end >= start); - } - } -@@ -99,17 +153,18 @@ - /// Ensure the kernel's virtual memory layout is free of overlaps. - #[kernel_test] - fn virt_mem_layout_has_no_overlaps() { -- let layout = virt_mem_layout().inner(); -- -- for (i, first) in layout.iter().enumerate() { -- for second in layout.iter().skip(i + 1) { -- let first_range = first.virtual_range; -- let second_range = second.virtual_range; -- -- assert!(!first_range().contains(second_range().start())); -- assert!(!first_range().contains(second_range().end())); -- assert!(!second_range().contains(first_range().start())); -- assert!(!second_range().contains(first_range().end())); -+ let layout = [ -+ virt_stack_page_desc().into_usize_range_inclusive(), -+ virt_ro_page_desc().into_usize_range_inclusive(), -+ virt_data_page_desc().into_usize_range_inclusive(), -+ ]; -+ -+ for (i, first_range) in layout.iter().enumerate() { -+ for second_range in layout.iter().skip(i + 1) { -+ assert!(!first_range.contains(second_range.start())); -+ assert!(!first_range.contains(second_range.end())); -+ assert!(!second_range.contains(first_range.start())); -+ assert!(!second_range.contains(first_range.end())); - } - } - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs -@@ -3,9 +3,41 @@ - // Copyright (c) 2018-2020 Andre Richter - - //! BSP Memory Management. -+//! -+//! The physical memory layout after the kernel has been loaded by the Raspberry's firmware, which -+//! copies the binary to 0x8_0000: -+//! -+//! +---------------------------------------------+ -+//! | | 0x0 -+//! | Unmapped | -+//! | | 0x6_FFFF -+//! +---------------------------------------------+ -+//! | BOOT_CORE_STACK_START | 0x7_0000 -+//! | | ^ -+//! | ... | | Stack growth direction -+//! | | | -+//! | BOOT_CORE_STACK_END_INCLUSIVE | 0x7_FFFF -+//! +---------------------------------------------+ -+//! | RO_START == BOOT_CORE_STACK_END | 0x8_0000 -+//! | | -+//! | | -+//! | .text | -+//! | .exception_vectors | -+//! | .rodata | -+//! | | -+//! | RO_END_INCLUSIVE | 0x8_0000 + __ro_size - 1 -+//! +---------------------------------------------+ -+//! | RO_END == DATA_START | 0x8_0000 + __ro_size -+//! | | -+//! | .data | -+//! | .bss | -+//! | | -+//! | DATA_END_INCLUSIVE | 0x8_0000 + __ro_size + __data_size - 1 -+//! +---------------------------------------------+ - - pub mod mmu; - -+use crate::memory::mmu::{Address, Physical, Virtual}; - use core::{cell::UnsafeCell, ops::RangeInclusive}; - - //-------------------------------------------------------------------------------------------------- -@@ -17,34 +49,39 @@ - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; - static __ro_start: UnsafeCell<()>; -- static __ro_end: UnsafeCell<()>; -+ static __ro_size: UnsafeCell<()>; -+ static __data_size: UnsafeCell<()>; - } - - //-------------------------------------------------------------------------------------------------- - // Public Definitions - //-------------------------------------------------------------------------------------------------- - --/// The board's memory map. -+/// The board's physical memory map. - #[rustfmt::skip] - pub(super) mod map { -- pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; -+ use super::*; - -- pub const BOOT_CORE_STACK_END: usize = 0x8_0000; -- -- pub const GPIO_OFFSET: usize = 0x0020_0000; -- pub const UART_OFFSET: usize = 0x0020_1000; -+ pub const BOOT_CORE_STACK_SIZE: usize = 0x1_0000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - -- pub const START: usize = 0x3F00_0000; -- pub const PERIPHERAL_INTERRUPT_CONTROLLER_START: usize = START + 0x0000_B200; -- pub const GPIO_START: usize = START + GPIO_OFFSET; -- pub const PL011_UART_START: usize = START + UART_OFFSET; -- pub const LOCAL_INTERRUPT_CONTROLLER_START: usize = 0x4000_0000; -- pub const END_INCLUSIVE: usize = 0x4000_FFFF; -+ pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); -+ pub const PERIPHERAL_IC_SIZE: usize = 0x24; -+ -+ pub const GPIO_START: Address = Address::new(0x3F20_0000); -+ pub const GPIO_SIZE: usize = 0xA0; -+ -+ pub const PL011_UART_START: Address = Address::new(0x3F20_1000); -+ pub const PL011_UART_SIZE: usize = 0x48; -+ -+ pub const LOCAL_IC_START: Address = Address::new(0x4000_0000); -+ pub const LOCAL_IC_SIZE: usize = 0x100; -+ -+ pub const END: Address = Address::new(0x4001_0000); - } - - /// Physical devices. -@@ -52,13 +89,22 @@ - pub mod mmio { - use super::*; - -- pub const START: usize = 0xFE00_0000; -- pub const GPIO_START: usize = START + GPIO_OFFSET; -- pub const PL011_UART_START: usize = START + UART_OFFSET; -- pub const GICD_START: usize = 0xFF84_1000; -- pub const GICC_START: usize = 0xFF84_2000; -- pub const END_INCLUSIVE: usize = 0xFF84_FFFF; -+ pub const GPIO_START: Address = Address::new(0xFE20_0000); -+ pub const GPIO_SIZE: usize = 0xA0; -+ -+ pub const PL011_UART_START: Address = Address::new(0xFE20_1000); -+ pub const PL011_UART_SIZE: usize = 0x48; -+ -+ pub const GICD_START: Address = Address::new(0xFF84_1000); -+ pub const GICD_SIZE: usize = 0x824; -+ -+ pub const GICC_START: Address = Address::new(0xFF84_2000); -+ pub const GICC_SIZE: usize = 0x14; -+ -+ pub const END: Address = Address::new(0xFF85_0000); - } -+ -+ pub const END: Address = mmio::END; - } - - //-------------------------------------------------------------------------------------------------- -@@ -71,8 +117,8 @@ - /// - /// - Value is provided by the linker script and must be trusted as-is. - #[inline(always)] --fn ro_start() -> usize { -- unsafe { __ro_start.get() as usize } -+fn virt_ro_start() -> Address { -+ Address::new(unsafe { __ro_start.get() as usize }) - } - - /// Size of the Read-Only (RO) range of the kernel binary. -@@ -81,8 +127,42 @@ - /// - /// - Value is provided by the linker script and must be trusted as-is. - #[inline(always)] --fn ro_end() -> usize { -- unsafe { __ro_end.get() as usize } -+fn ro_size() -> usize { -+ unsafe { __ro_size.get() as usize } -+} -+ -+/// Start address of the data range. -+#[inline(always)] -+fn virt_data_start() -> Address { -+ virt_ro_start() + ro_size() -+} -+ -+/// Size of the data range. -+/// -+/// # Safety -+/// -+/// - Value is provided by the linker script and must be trusted as-is. -+#[inline(always)] -+fn data_size() -> usize { -+ unsafe { __data_size.get() as usize } -+} -+ -+/// Start address of the boot core's stack. -+#[inline(always)] -+fn virt_boot_core_stack_start() -> Address { -+ virt_ro_start() - map::BOOT_CORE_STACK_SIZE -+} -+ -+/// Size of the boot core's stack. -+#[inline(always)] -+fn boot_core_stack_size() -> usize { -+ map::BOOT_CORE_STACK_SIZE -+} -+ -+/// Exclusive end address of the physical address space. -+#[inline(always)] -+fn phys_addr_space_end() -> Address { -+ map::END - } - - //-------------------------------------------------------------------------------------------------- -@@ -91,8 +171,10 @@ - - /// Exclusive end address of the boot core's stack. - #[inline(always)] --pub fn boot_core_stack_end() -> usize { -- map::BOOT_CORE_STACK_END -+pub fn phys_boot_core_stack_end() -> Address { -+ // The binary is still identity mapped, so we don't need to convert here. -+ let end = virt_boot_core_stack_start().into_usize() + boot_core_stack_size(); -+ Address::new(end) - } - - /// Return the inclusive range spanning the .bss section. - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs ---- 14_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs -+++ 15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs -@@ -10,17 +10,20 @@ - pub mod exception; - pub mod memory; - -+use super::device_driver; -+use crate::memory::mmu::MMIODescriptor; -+use memory::map::mmio; -+ - //-------------------------------------------------------------------------------------------------- - // Global instances - //-------------------------------------------------------------------------------------------------- --use super::device_driver; - - static GPIO: device_driver::GPIO = -- unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; -+ unsafe { device_driver::GPIO::new(MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE)) }; - - static PL011_UART: device_driver::PL011Uart = unsafe { - device_driver::PL011Uart::new( -- memory::map::mmio::PL011_UART_START, -+ MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE), - exception::asynchronous::irq_map::PL011_UART, - ) - }; -@@ -28,14 +31,17 @@ - #[cfg(feature = "bsp_rpi3")] - static INTERRUPT_CONTROLLER: device_driver::InterruptController = unsafe { - device_driver::InterruptController::new( -- memory::map::mmio::LOCAL_INTERRUPT_CONTROLLER_START, -- memory::map::mmio::PERIPHERAL_INTERRUPT_CONTROLLER_START, -+ MMIODescriptor::new(mmio::LOCAL_IC_START, mmio::LOCAL_IC_SIZE), -+ MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE), - ) - }; - - #[cfg(feature = "bsp_rpi4")] - static INTERRUPT_CONTROLLER: device_driver::GICv2 = unsafe { -- device_driver::GICv2::new(memory::map::mmio::GICD_START, memory::map::mmio::GICC_START) -+ device_driver::GICv2::new( -+ MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE), -+ MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE), -+ ) - }; - - //-------------------------------------------------------------------------------------------------- - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/common.rs 15_virtual_mem_part2_mmio_remap/src/common.rs ---- 14_exceptions_part2_peripheral_IRQs/src/common.rs -+++ 15_virtual_mem_part2_mmio_remap/src/common.rs -@@ -0,0 +1,21 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! General purpose code. -+ -+/// Check if a value is aligned to a given size. -+#[inline(always)] -+pub const fn is_aligned(value: usize, alignment: usize) -> bool { -+ assert!(alignment.is_power_of_two()); -+ -+ (value & (alignment - 1)) == 0 -+} -+ -+/// Align down. -+#[inline(always)] -+pub const fn align_down(value: usize, alignment: usize) -> usize { -+ assert!(alignment.is_power_of_two()); -+ -+ value & !(alignment - 1) -+} - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/driver.rs 15_virtual_mem_part2_mmio_remap/src/driver.rs ---- 14_exceptions_part2_peripheral_IRQs/src/driver.rs -+++ 15_virtual_mem_part2_mmio_remap/src/driver.rs -@@ -31,6 +31,14 @@ - fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { - Ok(()) - } -+ -+ /// After MMIO remapping, returns the new virtual start address. -+ /// -+ /// This API assumes a driver has only a single, contiguous MMIO aperture, which will not be -+ /// the case for more complex devices. This API will likely change in future tutorials. -+ fn virt_mmio_start_addr(&self) -> Option { -+ None -+ } - } - - /// Device driver management functions. -@@ -38,15 +46,17 @@ - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. -- /// -- /// # Safety -- /// -- /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - -- /// Initialization code that runs after driver init. -+ /// Return only those drivers needed for the BSP's early printing functionality. - /// -- /// For example, device driver code that depends on other drivers already being online. -- fn post_device_driver_init(&self); -+ /// For example, the default UART. -+ fn early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; -+ -+ /// Return all drivers minus early-print drivers. -+ fn non_early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; -+ -+ /// Initialization code that runs after the early print driver init. -+ fn post_early_print_device_driver_init(&self); - } - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/lib.rs 15_virtual_mem_part2_mmio_remap/src/lib.rs ---- 14_exceptions_part2_peripheral_IRQs/src/lib.rs -+++ 15_virtual_mem_part2_mmio_remap/src/lib.rs -@@ -113,6 +113,7 @@ - - #![allow(incomplete_features)] - #![feature(asm)] -+#![feature(const_fn)] - #![feature(const_fn_fn_ptr_basics)] - #![feature(const_generics)] - #![feature(const_panic)] -@@ -138,6 +139,7 @@ - mod synchronization; - - pub mod bsp; -+pub mod common; - pub mod console; - pub mod cpu; - pub mod driver; - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/main.rs 15_virtual_mem_part2_mmio_remap/src/main.rs ---- 14_exceptions_part2_peripheral_IRQs/src/main.rs -+++ 15_virtual_mem_part2_mmio_remap/src/main.rs -@@ -26,21 +26,34 @@ - #[no_mangle] - unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; -- use memory::mmu::interface::MMU; - - exception::handling_init(); - -- if let Err(string) = memory::mmu::mmu().init() { -- panic!("MMU: {}", string); -+ if let Err(string) = memory::mmu::kernel_map_binary_and_enable_mmu() { -+ panic!("Enabling MMU failed: {}", string); - } -+ // Printing will silently fail fail from here on, because the driver's MMIO is not remapped yet. - -- for i in bsp::driver::driver_manager().all_device_drivers().iter() { -+ // Bring up the drivers needed for printing first. -+ for i in bsp::driver::driver_manager() -+ .early_print_device_drivers() -+ .iter() -+ { -+ // Any encountered errors cannot be printed yet, obviously, so just safely park the CPU. -+ i.init().unwrap_or_else(|_| cpu::wait_forever()); -+ } -+ bsp::driver::driver_manager().post_early_print_device_driver_init(); -+ // Printing available again from here on. -+ -+ // Now bring up the remaining drivers. -+ for i in bsp::driver::driver_manager() -+ .non_early_print_device_drivers() -+ .iter() -+ { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } -- bsp::driver::driver_manager().post_device_driver_init(); -- // println! is usable from here on. - - // Let device drivers register and enable their handlers with the interrupt controller. - for i in bsp::driver::driver_manager().all_device_drivers() { -@@ -66,8 +79,8 @@ - - info!("Booting on: {}", bsp::board_name()); - -- info!("MMU online. Special regions:"); -- bsp::memory::mmu::virt_mem_layout().print_layout(); -+ info!("MMU online:"); -+ memory::mmu::kernel_print_mappings(); - - let (_, privilege_level) = exception::current_privilege_level(); - info!("Current privilege level: {}", privilege_level); - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs 15_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs ---- 14_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs -+++ 15_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs -@@ -0,0 +1,221 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! A record of mapped pages. -+ -+use super::{ -+ AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, -+ PageSliceDescriptor, Physical, Virtual, -+}; -+use crate::{info, synchronization, synchronization::InitStateLock, warn}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+/// Type describing a virtual memory mapping. -+#[allow(missing_docs)] -+#[derive(Copy, Clone)] -+struct MappingRecordEntry { -+ pub users: [Option<&'static str>; 5], -+ pub phys_pages: PageSliceDescriptor, -+ pub virt_start_addr: Address, -+ pub attribute_fields: AttributeFields, -+} -+ -+struct MappingRecord { -+ inner: [Option; 12], -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Global instances -+//-------------------------------------------------------------------------------------------------- -+ -+static KERNEL_MAPPING_RECORD: InitStateLock = -+ InitStateLock::new(MappingRecord::new()); -+ -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl MappingRecordEntry { -+ pub fn new( -+ name: &'static str, -+ phys_pages: &PageSliceDescriptor, -+ virt_pages: &PageSliceDescriptor, -+ attr: &AttributeFields, -+ ) -> Self { -+ Self { -+ users: [Some(name), None, None, None, None], -+ phys_pages: *phys_pages, -+ virt_start_addr: virt_pages.start_addr(), -+ attribute_fields: *attr, -+ } -+ } -+ -+ fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { -+ if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { -+ return Ok(x); -+ }; -+ -+ Err("Storage for user info exhausted") -+ } -+ -+ pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { -+ let x = self.find_next_free_user()?; -+ *x = Some(user); -+ Ok(()) -+ } -+} -+ -+impl MappingRecord { -+ pub const fn new() -> Self { -+ Self { inner: [None; 12] } -+ } -+ -+ fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { -+ if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { -+ return Ok(x); -+ } -+ -+ Err("Storage for mapping info exhausted") -+ } -+ -+ fn find_duplicate( -+ &mut self, -+ phys_pages: &PageSliceDescriptor, -+ ) -> Option<&mut MappingRecordEntry> { -+ self.inner -+ .iter_mut() -+ .filter(|x| x.is_some()) -+ .map(|x| x.as_mut().unwrap()) -+ .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) -+ .find(|x| x.phys_pages == *phys_pages) -+ } -+ -+ pub fn add( -+ &mut self, -+ name: &'static str, -+ phys_pages: &PageSliceDescriptor, -+ virt_pages: &PageSliceDescriptor, -+ attr: &AttributeFields, -+ ) -> Result<(), &'static str> { -+ let x = self.find_next_free()?; -+ -+ *x = Some(MappingRecordEntry::new(name, phys_pages, virt_pages, attr)); -+ Ok(()) -+ } -+ -+ pub fn print(&self) { -+ const KIB_RSHIFT: u32 = 10; // log2(1024). -+ const MIB_RSHIFT: u32 = 20; // log2(1024 * 1024). -+ -+ info!(" -----------------------------------------------------------------------------------------------------------------"); -+ info!( -+ " {:^24} {:^24} {:^7} {:^9} {:^35}", -+ "Virtual", "Physical", "Size", "Attr", "Entity" -+ ); -+ info!(" -----------------------------------------------------------------------------------------------------------------"); -+ -+ for i in self -+ .inner -+ .iter() -+ .filter(|x| x.is_some()) -+ .map(|x| x.unwrap()) -+ { -+ let virt_start = i.virt_start_addr.into_usize(); -+ let virt_end_inclusive = virt_start + i.phys_pages.size() - 1; -+ let phys_start = i.phys_pages.start_addr().into_usize(); -+ let phys_end_inclusive = i.phys_pages.end_addr_inclusive().into_usize(); -+ let size = i.phys_pages.size(); -+ -+ let (size, unit) = if (size >> MIB_RSHIFT) > 0 { -+ (size >> MIB_RSHIFT, "MiB") -+ } else if (size >> KIB_RSHIFT) > 0 { -+ (size >> KIB_RSHIFT, "KiB") -+ } else { -+ (size, "Byte") -+ }; -+ -+ let attr = match i.attribute_fields.mem_attributes { -+ MemAttributes::CacheableDRAM => "C", -+ MemAttributes::Device => "Dev", -+ }; -+ -+ let acc_p = match i.attribute_fields.acc_perms { -+ AccessPermissions::ReadOnly => "RO", -+ AccessPermissions::ReadWrite => "RW", -+ }; -+ -+ let xn = if i.attribute_fields.execute_never { -+ "XN" -+ } else { -+ "X" -+ }; -+ -+ info!( -+ " {:#011X}..{:#011X} --> {:#011X}..{:#011X} | \ -+ {: >3} {} | {: <3} {} {: <2} | {}", -+ virt_start, -+ virt_end_inclusive, -+ phys_start, -+ phys_end_inclusive, -+ size, -+ unit, -+ attr, -+ acc_p, -+ xn, -+ i.users[0].unwrap() -+ ); -+ -+ for k in i.users[1..].iter() { -+ if let Some(additional_user) = *k { -+ info!( -+ " | {}", -+ additional_user -+ ); -+ } -+ } -+ } -+ -+ info!(" -----------------------------------------------------------------------------------------------------------------"); -+ } -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+use synchronization::interface::ReadWriteEx; -+ -+/// Add an entry to the mapping info record. -+pub fn kernel_add( -+ name: &'static str, -+ phys_pages: &PageSliceDescriptor, -+ virt_pages: &PageSliceDescriptor, -+ attr: &AttributeFields, -+) -> Result<(), &'static str> { -+ KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, phys_pages, virt_pages, attr)) -+} -+ -+pub fn kernel_find_and_insert_mmio_duplicate( -+ phys_mmio_descriptor: &MMIODescriptor, -+ new_user: &'static str, -+) -> Option> { -+ let phys_pages: PageSliceDescriptor = phys_mmio_descriptor.clone().into(); -+ -+ KERNEL_MAPPING_RECORD.write(|mr| { -+ let dup = mr.find_duplicate(&phys_pages)?; -+ -+ if let Err(x) = dup.add_user(new_user) { -+ warn!("{}", x); -+ } -+ -+ Some(dup.virt_start_addr) -+ }) -+} -+ -+/// Human-readable print of all recorded kernel mappings. -+pub fn kernel_print() { -+ KERNEL_MAPPING_RECORD.read(|mr| mr.print()); -+} - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs 15_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs ---- 14_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs -+++ 15_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs -@@ -0,0 +1,283 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020 Andre Richter -+ -+//! Memory Management Unit Types. -+ -+use crate::{bsp, common}; -+use core::{convert::From, marker::PhantomData, ops::RangeInclusive}; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+use super::interface::TranslationGranule; -+ -+/// Metadata trait for marking the type of an address. -+pub trait AddressType: Copy + Clone + PartialOrd + PartialEq {} -+ -+/// Zero-sized type to mark a physical address. -+#[derive(Copy, Clone, PartialOrd, PartialEq)] -+pub enum Physical {} -+ -+/// Zero-sized type to mark a virtual address. -+#[derive(Copy, Clone, PartialOrd, PartialEq)] -+pub enum Virtual {} -+ -+/// Generic address type. -+#[derive(Copy, Clone, PartialOrd, PartialEq)] -+pub struct Address { -+ value: usize, -+ _address_type: PhantomData, -+} -+ -+/// Generic page type. -+#[repr(C)] -+pub struct Page { -+ inner: [u8; bsp::memory::mmu::KernelGranule::SIZE], -+ _address_type: PhantomData, -+} -+ -+/// Type describing a slice of pages. -+#[derive(Copy, Clone, PartialOrd, PartialEq)] -+pub struct PageSliceDescriptor { -+ start: Address, -+ num_pages: usize, -+} -+ -+/// Architecture agnostic memory attributes. -+#[allow(missing_docs)] -+#[derive(Copy, Clone, PartialOrd, PartialEq)] -+pub enum MemAttributes { -+ CacheableDRAM, -+ Device, -+} -+ -+/// Architecture agnostic access permissions. -+#[allow(missing_docs)] -+#[derive(Copy, Clone)] -+pub enum AccessPermissions { -+ ReadOnly, -+ ReadWrite, -+} -+ -+/// Collection of memory attributes. -+#[allow(missing_docs)] -+#[derive(Copy, Clone)] -+pub struct AttributeFields { -+ pub mem_attributes: MemAttributes, -+ pub acc_perms: AccessPermissions, -+ pub execute_never: bool, -+} -+ -+/// An MMIO descriptor for use in device drivers. -+#[derive(Copy, Clone)] -+pub struct MMIODescriptor { -+ start_addr: Address, -+ size: usize, -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+impl AddressType for Physical {} -+impl AddressType for Virtual {} -+ -+//------------------------------------------------------------------------------ -+// Address -+//------------------------------------------------------------------------------ -+ -+impl Address { -+ /// Create an instance. -+ pub const fn new(value: usize) -> Self { -+ Self { -+ value, -+ _address_type: PhantomData, -+ } -+ } -+ -+ /// Align down. -+ pub const fn align_down(self, alignment: usize) -> Self { -+ let aligned = common::align_down(self.value, alignment); -+ -+ Self { -+ value: aligned, -+ _address_type: PhantomData, -+ } -+ } -+ -+ /// Converts `Address` into an usize. -+ pub const fn into_usize(self) -> usize { -+ self.value -+ } -+} -+ -+impl core::ops::Add for Address { -+ type Output = Self; -+ -+ fn add(self, other: usize) -> Self { -+ Self { -+ value: self.value + other, -+ _address_type: PhantomData, -+ } -+ } -+} -+ -+impl core::ops::Sub for Address { -+ type Output = Self; -+ -+ fn sub(self, other: usize) -> Self { -+ Self { -+ value: self.value - other, -+ _address_type: PhantomData, -+ } -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// Page -+//------------------------------------------------------------------------------ -+ -+impl Page { -+ /// Get a pointer to the instance. -+ pub const fn as_ptr(&self) -> *const Page { -+ self as *const _ -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// PageSliceDescriptor -+//------------------------------------------------------------------------------ -+ -+impl PageSliceDescriptor { -+ /// Create an instance. -+ pub const fn from_addr(start: Address, num_pages: usize) -> Self { -+ assert!(common::is_aligned( -+ start.into_usize(), -+ bsp::memory::mmu::KernelGranule::SIZE -+ )); -+ assert!(num_pages > 0); -+ -+ Self { start, num_pages } -+ } -+ -+ /// Return a pointer to the first page of the described slice. -+ const fn first_page_ptr(&self) -> *const Page { -+ self.start.into_usize() as *const _ -+ } -+ -+ /// Return the number of Pages the slice describes. -+ pub const fn num_pages(&self) -> usize { -+ self.num_pages -+ } -+ -+ /// Return the memory size this descriptor spans. -+ pub const fn size(&self) -> usize { -+ self.num_pages * bsp::memory::mmu::KernelGranule::SIZE -+ } -+ -+ /// Return the start address. -+ pub const fn start_addr(&self) -> Address { -+ self.start -+ } -+ -+ /// Return the exclusive end address. -+ pub fn end_addr(&self) -> Address { -+ self.start + self.size() -+ } -+ -+ /// Return the inclusive end address. -+ pub fn end_addr_inclusive(&self) -> Address { -+ self.start + (self.size() - 1) -+ } -+ -+ /// Return a non-mutable slice of Pages. -+ /// -+ /// # Safety -+ /// -+ /// - Same as applies for `core::slice::from_raw_parts`. -+ pub unsafe fn as_slice(&self) -> &[Page] { -+ core::slice::from_raw_parts(self.first_page_ptr(), self.num_pages) -+ } -+ -+ /// Return the inclusive address range of the slice. -+ pub fn into_usize_range_inclusive(self) -> RangeInclusive { -+ RangeInclusive::new( -+ self.start_addr().into_usize(), -+ self.end_addr_inclusive().into_usize(), -+ ) -+ } -+} -+ -+impl From> for PageSliceDescriptor { -+ fn from(desc: PageSliceDescriptor) -> Self { -+ Self { -+ start: Address::new(desc.start.into_usize()), -+ num_pages: desc.num_pages, -+ } -+ } -+} -+ -+impl From> for PageSliceDescriptor { -+ fn from(desc: MMIODescriptor) -> Self { -+ let start_page_addr = desc -+ .start_addr -+ .align_down(bsp::memory::mmu::KernelGranule::SIZE); -+ -+ let len = ((desc.end_addr_inclusive().into_usize() - start_page_addr.into_usize()) -+ >> bsp::memory::mmu::KernelGranule::SHIFT) -+ + 1; -+ -+ Self { -+ start: start_page_addr, -+ num_pages: len, -+ } -+ } -+} -+ -+//------------------------------------------------------------------------------ -+// MMIODescriptor -+//------------------------------------------------------------------------------ -+ -+impl MMIODescriptor { -+ /// Create an instance. -+ pub const fn new(start_addr: Address, size: usize) -> Self { -+ assert!(size > 0); -+ -+ Self { start_addr, size } -+ } -+ -+ /// Return the start address. -+ pub const fn start_addr(&self) -> Address { -+ self.start_addr -+ } -+ -+ /// Return the inclusive end address. -+ pub fn end_addr_inclusive(&self) -> Address { -+ self.start_addr + (self.size - 1) -+ } -+ -+ /// Return the size. -+ pub const fn size(&self) -> usize { -+ self.size -+ } -+} -+ -+//-------------------------------------------------------------------------------------------------- -+// Testing -+//-------------------------------------------------------------------------------------------------- -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ use test_macros::kernel_test; -+ -+ /// Check if the size of `struct Page` is as expected. -+ #[kernel_test] -+ fn size_of_page_equals_granule_size() { -+ assert_eq!( -+ core::mem::size_of::>(), -+ bsp::memory::mmu::KernelGranule::SIZE -+ ); -+ } -+} - -diff -uNr 14_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 15_virtual_mem_part2_mmio_remap/src/memory/mmu.rs ---- 14_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs -+++ 15_virtual_mem_part2_mmio_remap/src/memory/mmu.rs -@@ -3,23 +3,18 @@ - // Copyright (c) 2020 Andre Richter - - //! Memory Management Unit. --//! --//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file --//! provides types for composing an architecture-agnostic description of the kernel 's virtual --//! memory layout. --//! --//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` --//! function. --//! --//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and --//! install respective translation tables. - - #[cfg(target_arch = "aarch64")] - #[path = "../_arch/aarch64/memory/mmu.rs"] - mod arch_mmu; - pub use arch_mmu::*; - --use core::{fmt, ops::RangeInclusive}; -+mod mapping_record; -+mod types; -+ -+use crate::{bsp, synchronization, warn}; -+ -+pub use types::*; - - //-------------------------------------------------------------------------------------------------- - // Public Definitions -@@ -27,178 +22,229 @@ - - /// Memory Management interfaces. - pub mod interface { -+ use super::*; -+ -+ /// Describes the characteristics of a translation granule. -+ #[allow(missing_docs)] -+ pub trait TranslationGranule { -+ const SIZE: usize; -+ const MASK: usize = Self::SIZE - 1; -+ const SHIFT: usize; -+ } -+ -+ /// Translation table operations. -+ pub trait TranslationTable { -+ /// Anything that needs to run before any of the other provided functions can be used. -+ /// -+ /// # Safety -+ /// -+ /// - Implementor must ensure that this function can run only once or is harmless if invoked -+ /// multiple times. -+ unsafe fn init(&mut self); -+ -+ /// The translation table's base address to be used for programming the MMU. -+ fn phys_base_address(&self) -> Address; -+ -+ /// Map the given physical pages to the given virtual pages. -+ /// -+ /// # Safety -+ /// -+ /// - Using wrong attributes can cause multiple issues of different nature in the system. -+ /// - It is not required that the architectural implementation prevents aliasing. That is, -+ /// mapping to the same physical memory using multiple virtual addresses, which would -+ /// break Rust's ownership assumptions. This should be protected against in this module -+ /// (the kernel's generic MMU code). -+ unsafe fn map_pages_at( -+ &mut self, -+ phys_pages: &PageSliceDescriptor, -+ virt_pages: &PageSliceDescriptor, -+ attr: &AttributeFields, -+ ) -> Result<(), &'static str>; -+ -+ /// Obtain a free virtual page slice in the MMIO region. -+ /// -+ /// The "MMIO region" is a distinct region of the implementor's choice, which allows -+ /// differentiating MMIO addresses from others. This can speed up debugging efforts. -+ /// Ideally, those MMIO addresses are also standing out visually so that a human eye can -+ /// identify them. For example, by allocating them from near the end of the virtual address -+ /// space. -+ fn next_mmio_virt_page_slice( -+ &mut self, -+ num_pages: usize, -+ ) -> Result, &'static str>; -+ -+ /// Check if a virtual page splice is in the "MMIO region". -+ fn is_virt_page_slice_mmio(&self, virt_pages: &PageSliceDescriptor) -> bool; -+ } - - /// MMU functions. - pub trait MMU { -- /// Called by the kernel during early init. Supposed to take the translation tables from the -- /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. -+ /// Turns on the MMU. - /// - /// # Safety - /// -+ /// - Must only be called after the kernel translation tables have been init()'ed. - /// - Changes the HW's global state. -- unsafe fn init(&self) -> Result<(), &'static str>; -+ unsafe fn enable( -+ &self, -+ phys_kernel_table_base_addr: Address, -+ ) -> Result<(), &'static str>; - } - } - --/// Architecture agnostic translation types. --#[allow(missing_docs)] --#[derive(Copy, Clone)] --pub enum Translation { -- Identity, -- Offset(usize), --} -- --/// Architecture agnostic memory attributes. --#[allow(missing_docs)] --#[derive(Copy, Clone)] --pub enum MemAttributes { -- CacheableDRAM, -- Device, --} -+//-------------------------------------------------------------------------------------------------- -+// Private Code -+//-------------------------------------------------------------------------------------------------- -+use interface::{TranslationTable, MMU}; -+use synchronization::interface::ReadWriteEx; - --/// Architecture agnostic access permissions. --#[allow(missing_docs)] --#[derive(Copy, Clone)] --pub enum AccessPermissions { -- ReadOnly, -- ReadWrite, --} -+/// Map pages in the kernel's translation tables. -+/// -+/// No input checks done, input is passed through to the architectural implementation. -+/// -+/// # Safety -+/// -+/// - See `map_pages_at()`. -+/// - Does not prevent aliasing. -+unsafe fn kernel_map_pages_at_unchecked( -+ name: &'static str, -+ phys_pages: &PageSliceDescriptor, -+ virt_pages: &PageSliceDescriptor, -+ attr: &AttributeFields, -+) -> Result<(), &'static str> { -+ arch_mmu::kernel_translation_tables() -+ .write(|tables| tables.map_pages_at(phys_pages, virt_pages, attr))?; - --/// Collection of memory attributes. --#[allow(missing_docs)] --#[derive(Copy, Clone)] --pub struct AttributeFields { -- pub mem_attributes: MemAttributes, -- pub acc_perms: AccessPermissions, -- pub execute_never: bool, --} -+ if let Err(x) = mapping_record::kernel_add(name, phys_pages, virt_pages, attr) { -+ warn!("{}", x); -+ } - --/// Architecture agnostic descriptor for a memory range. --#[allow(missing_docs)] --pub struct TranslationDescriptor { -- pub name: &'static str, -- pub virtual_range: fn() -> RangeInclusive, -- pub physical_range_translation: Translation, -- pub attribute_fields: AttributeFields, -+ Ok(()) - } - --/// Type for expressing the kernel's virtual memory layout. --pub struct KernelVirtualLayout { -- /// The last (inclusive) address of the address space. -- max_virt_addr_inclusive: usize, -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+use interface::TranslationGranule; - -- /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. -- inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], -+/// Raw mapping of virtual to physical pages in the kernel translation tables. -+/// -+/// Prevents mapping into the MMIO range of the tables. -+/// -+/// # Safety -+/// -+/// - See `kernel_map_pages_at_unchecked()`. -+/// - Does not prevent aliasing. Currently, we have to trust the callers. -+pub unsafe fn kernel_map_pages_at( -+ name: &'static str, -+ phys_pages: &PageSliceDescriptor, -+ virt_pages: &PageSliceDescriptor, -+ attr: &AttributeFields, -+) -> Result<(), &'static str> { -+ let is_mmio = arch_mmu::kernel_translation_tables() -+ .read(|tables| tables.is_virt_page_slice_mmio(virt_pages)); -+ if is_mmio { -+ return Err("Attempt to manually map into MMIO region"); -+ } -+ -+ kernel_map_pages_at_unchecked(name, phys_pages, virt_pages, attr)?; -+ -+ Ok(()) -+} -+ -+/// MMIO remapping in the kernel translation tables. -+/// -+/// Typically used by device drivers. -+/// -+/// # Safety -+/// -+/// - Same as `kernel_map_pages_at_unchecked()`, minus the aliasing part. -+pub unsafe fn kernel_map_mmio( -+ name: &'static str, -+ phys_mmio_descriptor: &MMIODescriptor, -+) -> Result, &'static str> { -+ let phys_pages: PageSliceDescriptor = phys_mmio_descriptor.clone().into(); -+ let offset_into_start_page = -+ phys_mmio_descriptor.start_addr().into_usize() & bsp::memory::mmu::KernelGranule::MASK; -+ -+ // Check if an identical page slice has been mapped for another driver. If so, reuse it. -+ let virt_addr = if let Some(addr) = -+ mapping_record::kernel_find_and_insert_mmio_duplicate(phys_mmio_descriptor, name) -+ { -+ addr -+ // Otherwise, allocate a new virtual page slice and map it. -+ } else { -+ let virt_pages: PageSliceDescriptor = arch_mmu::kernel_translation_tables() -+ .write(|tables| tables.next_mmio_virt_page_slice(phys_pages.num_pages()))?; -+ -+ kernel_map_pages_at_unchecked( -+ name, -+ &phys_pages, -+ &virt_pages, -+ &AttributeFields { -+ mem_attributes: MemAttributes::Device, -+ acc_perms: AccessPermissions::ReadWrite, -+ execute_never: true, -+ }, -+ )?; -+ -+ virt_pages.start_addr() -+ }; -+ -+ Ok(virt_addr + offset_into_start_page) -+} -+ -+/// Map the kernel's binary and enable the MMU. -+/// -+/// # Safety -+/// -+/// - Crucial function during kernel init. Changes the the complete memory view of the processor. -+pub unsafe fn kernel_map_binary_and_enable_mmu() -> Result<(), &'static str> { -+ let phys_base_addr = arch_mmu::kernel_translation_tables().write(|tables| { -+ tables.init(); -+ tables.phys_base_address() -+ }); -+ -+ bsp::memory::mmu::kernel_map_binary()?; -+ arch_mmu::mmu().enable(phys_base_addr) -+} -+ -+/// Human-readable print of all recorded kernel mappings. -+pub fn kernel_print_mappings() { -+ mapping_record::kernel_print() - } - - //-------------------------------------------------------------------------------------------------- --// Public Code -+// Testing - //-------------------------------------------------------------------------------------------------- - --impl Default for AttributeFields { -- fn default() -> AttributeFields { -- AttributeFields { -- mem_attributes: MemAttributes::CacheableDRAM, -- acc_perms: AccessPermissions::ReadWrite, -- execute_never: true, -- } -- } --} -- --/// Human-readable output of a TranslationDescriptor. --impl fmt::Display for TranslationDescriptor { -- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -- // Call the function to which self.range points, and dereference the result, which causes -- // Rust to copy the value. -- let start = *(self.virtual_range)().start(); -- let end = *(self.virtual_range)().end(); -- let size = end - start + 1; -- -- // log2(1024). -- const KIB_RSHIFT: u32 = 10; -- -- // log2(1024 * 1024). -- const MIB_RSHIFT: u32 = 20; -- -- let (size, unit) = if (size >> MIB_RSHIFT) > 0 { -- (size >> MIB_RSHIFT, "MiB") -- } else if (size >> KIB_RSHIFT) > 0 { -- (size >> KIB_RSHIFT, "KiB") -- } else { -- (size, "Byte") -- }; -- -- let attr = match self.attribute_fields.mem_attributes { -- MemAttributes::CacheableDRAM => "C", -- MemAttributes::Device => "Dev", -- }; -- -- let acc_p = match self.attribute_fields.acc_perms { -- AccessPermissions::ReadOnly => "RO", -- AccessPermissions::ReadWrite => "RW", -- }; -- -- let xn = if self.attribute_fields.execute_never { -- "PXN" -- } else { -- "PX" -- }; -- -- write!( -- f, -- " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", -- start, end, size, unit, attr, acc_p, xn, self.name -- ) -- } --} -- --impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { -- /// Create a new instance. -- pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { -- Self { -- max_virt_addr_inclusive: max, -- inner: layout, -- } -- } -- -- /// For a virtual address, find and return the physical output address and corresponding -- /// attributes. -- /// -- /// If the address is not found in `inner`, return an identity mapped default with normal -- /// cacheable DRAM attributes. -- pub fn virt_addr_properties( -- &self, -- virt_addr: usize, -- ) -> Result<(usize, AttributeFields), &'static str> { -- if virt_addr > self.max_virt_addr_inclusive { -- return Err("Address out of range"); -- } -- -- for i in self.inner.iter() { -- if (i.virtual_range)().contains(&virt_addr) { -- let output_addr = match i.physical_range_translation { -- Translation::Identity => virt_addr, -- Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), -- }; -- -- return Ok((output_addr, i.attribute_fields)); -- } -- } -- -- Ok((virt_addr, AttributeFields::default())) -- } -- -- /// Print the memory layout. -- pub fn print_layout(&self) { -- use crate::info; -- -- for i in self.inner.iter() { -- info!("{}", i); -- } -- } -- -- #[cfg(test)] -- pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { -- &self.inner -+#[cfg(test)] -+mod tests { -+ use super::*; -+ use test_macros::kernel_test; -+ -+ /// Sanity checks for the kernel TranslationTable implementation. -+ #[kernel_test] -+ fn translationtable_implementation_sanity() { -+ // Need to take care that `tables` fits into the stack. -+ let mut tables = MinSizeArchTranslationTable::new(); -+ -+ unsafe { tables.init() }; -+ -+ let x = tables.next_mmio_virt_page_slice(0); -+ assert!(x.is_err()); -+ -+ let x = tables.next_mmio_virt_page_slice(1_0000_0000); -+ assert!(x.is_err()); -+ -+ let x = tables.next_mmio_virt_page_slice(2).unwrap(); -+ assert_eq!(x.size(), bsp::memory::mmu::KernelGranule::SIZE * 2); -+ -+ assert_eq!(tables.is_virt_page_slice_mmio(&x), true); -+ -+ assert_eq!( -+ tables.is_virt_page_slice_mmio(&PageSliceDescriptor::from_addr(Address::new(0), 1)), -+ false -+ ); - } - } - -diff -uNr 14_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs 15_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs ---- 14_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs -+++ 15_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs -@@ -21,7 +21,7 @@ - - #[no_mangle] - unsafe fn kernel_init() -> ! { -- use memory::mmu::interface::MMU; -+ use libkernel::driver::interface::DriverManager; - - bsp::console::qemu_bring_up_console(); - -@@ -30,10 +30,22 @@ - - exception::handling_init(); - -- if let Err(string) = memory::mmu::mmu().init() { -- println!("MMU: {}", string); -+ if let Err(string) = memory::mmu::kernel_map_binary_and_enable_mmu() { -+ println!("Enabling MMU failed: {}", string); - cpu::qemu_exit_failure() - } -+ // Printing will silently fail fail from here on, because the driver's MMIO is not remapped yet. -+ -+ // Bring up the drivers needed for printing first. -+ for i in bsp::driver::driver_manager() -+ .early_print_device_drivers() -+ .iter() -+ { -+ // Any encountered errors cannot be printed yet, obviously, so just safely park the CPU. -+ i.init().unwrap_or_else(|_| cpu::qemu_exit_failure()); -+ } -+ bsp::driver::driver_manager().post_early_print_device_driver_init(); -+ // Printing available again from here on. - - println!("Writing beyond mapped area to address 9 GiB..."); - let big_addr: u64 = 9 * 1024 * 1024 * 1024; - -``` diff --git a/15_virtual_mem_part2_mmio_remap/build.rs b/15_virtual_mem_part2_mmio_remap/build.rs deleted file mode 100644 index 40ee0284d..000000000 --- a/15_virtual_mem_part2_mmio_remap/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -use std::env; - -fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); - - println!("cargo:rerun-if-changed={}", linker_file); -} diff --git a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu.rs b/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu.rs deleted file mode 100644 index c68f1817d..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - // Expect the boot core to start in EL2. - if (bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id()) - && (CurrentEL.get() == CurrentEL::EL::EL2.value) - { - el2_to_el1_transition() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} - -/// Transition from EL2 to EL1. -/// -/// # Safety -/// -/// - The HW state of EL1 must be prepared in a sound way. -/// - Exception return from EL2 must must continue execution in EL1 with -/// `runtime_init::runtime_init()`. -#[inline(always)] -unsafe fn el2_to_el1_transition() -> ! { - use crate::runtime_init; - - // Enable timer counter registers for EL1. - CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); - - // No offset for reading the counters. - CNTVOFF_EL2.set(0); - - // Set EL1 execution state to AArch64. - HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); - - // Set up a simulated exception return. - // - // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a - // stack pointer. - SPSR_EL2.write( - SPSR_EL2::D::Masked - + SPSR_EL2::A::Masked - + SPSR_EL2::I::Masked - + SPSR_EL2::F::Masked - + SPSR_EL2::M::EL1h, - ); - - // Second, let the link register point to runtime_init(). - ELR_EL2.set(runtime_init::runtime_init as *const () as u64); - - // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. - SP_EL1.set(bsp::memory::phys_boot_core_stack_end().into_usize() as u64); - - // Use `eret` to "return" to EL1. This results in execution of runtime_init() in EL1. - asm::eret() -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -pub use asm::nop; - -/// Pause execution on the core. -#[inline(always)] -pub fn wait_forever() -> ! { - loop { - asm::wfe() - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- -use qemu_exit::QEMUExit; - -const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); - -/// Make the host QEMU binary execute `exit(1)`. -pub fn qemu_exit_failure() -> ! { - QEMU_EXIT_HANDLE.exit_failure() -} - -/// Make the host QEMU binary execute `exit(0)`. -pub fn qemu_exit_success() -> ! { - QEMU_EXIT_HANDLE.exit_success() -} diff --git a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/smp.rs b/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.S b/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.S deleted file mode 100644 index ee3b5497e..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.S +++ /dev/null @@ -1,138 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -/// Call the function provided by parameter `\handler` after saving the exception context. Provide -/// the context as the first parameter to '\handler'. -.macro CALL_WITH_CONTEXT handler - // Make room on the stack for the exception context. - sub sp, sp, #16 * 17 - - // Store all general purpose registers on the stack. - stp x0, x1, [sp, #16 * 0] - stp x2, x3, [sp, #16 * 1] - stp x4, x5, [sp, #16 * 2] - stp x6, x7, [sp, #16 * 3] - stp x8, x9, [sp, #16 * 4] - stp x10, x11, [sp, #16 * 5] - stp x12, x13, [sp, #16 * 6] - stp x14, x15, [sp, #16 * 7] - stp x16, x17, [sp, #16 * 8] - stp x18, x19, [sp, #16 * 9] - stp x20, x21, [sp, #16 * 10] - stp x22, x23, [sp, #16 * 11] - stp x24, x25, [sp, #16 * 12] - stp x26, x27, [sp, #16 * 13] - stp x28, x29, [sp, #16 * 14] - - // Add the exception link register (ELR_EL1) and the saved program status (SPSR_EL1). - mrs x1, ELR_EL1 - mrs x2, SPSR_EL1 - - stp lr, x1, [sp, #16 * 15] - str x2, [sp, #16 * 16] - - // x0 is the first argument for the function called through `\handler`. - mov x0, sp - - // Call `\handler`. - bl \handler - - // After returning from exception handling code, replay the saved context and return via `eret`. - b __exception_restore_context -.endm - -.macro FIQ_SUSPEND -1: wfe - b 1b -.endm - -//-------------------------------------------------------------------------------------------------- -// The exception vector table. -//-------------------------------------------------------------------------------------------------- -.section .exception_vectors, "ax", @progbits - -// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. -.align 11 - -// Export a symbol for the Rust code to use. -__exception_vector_start: - -// Current exception level with SP_EL0. -// -// .org sets the offset relative to section start. -// -// # Safety -// -// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. -.org 0x000 - CALL_WITH_CONTEXT current_el0_synchronous -.org 0x080 - CALL_WITH_CONTEXT current_el0_irq -.org 0x100 - FIQ_SUSPEND -.org 0x180 - CALL_WITH_CONTEXT current_el0_serror - -// Current exception level with SP_ELx, x > 0. -.org 0x200 - CALL_WITH_CONTEXT current_elx_synchronous -.org 0x280 - CALL_WITH_CONTEXT current_elx_irq -.org 0x300 - FIQ_SUSPEND -.org 0x380 - CALL_WITH_CONTEXT current_elx_serror - -// Lower exception level, AArch64 -.org 0x400 - CALL_WITH_CONTEXT lower_aarch64_synchronous -.org 0x480 - CALL_WITH_CONTEXT lower_aarch64_irq -.org 0x500 - FIQ_SUSPEND -.org 0x580 - CALL_WITH_CONTEXT lower_aarch64_serror - -// Lower exception level, AArch32 -.org 0x600 - CALL_WITH_CONTEXT lower_aarch32_synchronous -.org 0x680 - CALL_WITH_CONTEXT lower_aarch32_irq -.org 0x700 - FIQ_SUSPEND -.org 0x780 - CALL_WITH_CONTEXT lower_aarch32_serror -.org 0x800 - -//-------------------------------------------------------------------------------------------------- -// Helper functions -//-------------------------------------------------------------------------------------------------- -.section .text - -__exception_restore_context: - ldr w19, [sp, #16 * 16] - ldp lr, x20, [sp, #16 * 15] - - msr SPSR_EL1, x19 - msr ELR_EL1, x20 - - ldp x0, x1, [sp, #16 * 0] - ldp x2, x3, [sp, #16 * 1] - ldp x4, x5, [sp, #16 * 2] - ldp x6, x7, [sp, #16 * 3] - ldp x8, x9, [sp, #16 * 4] - ldp x10, x11, [sp, #16 * 5] - ldp x12, x13, [sp, #16 * 6] - ldp x14, x15, [sp, #16 * 7] - ldp x16, x17, [sp, #16 * 8] - ldp x18, x19, [sp, #16 * 9] - ldp x20, x21, [sp, #16 * 10] - ldp x22, x23, [sp, #16 * 11] - ldp x24, x25, [sp, #16 * 12] - ldp x26, x27, [sp, #16 * 13] - ldp x28, x29, [sp, #16 * 14] - - add sp, sp, #16 * 17 - - eret diff --git a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.rs b/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.rs deleted file mode 100644 index a4451cde6..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.rs +++ /dev/null @@ -1,260 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural synchronous and asynchronous exception handling. - -use crate::{bsp, exception}; -use core::{cell::UnsafeCell, fmt}; -use cortex_a::{barrier, regs::*}; -use register::InMemoryRegister; - -// Assembly counterpart to this file. -global_asm!(include_str!("exception.S")); - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Wrapper struct for memory copy of SPSR_EL1. -#[repr(transparent)] -struct SpsrEL1(InMemoryRegister); - -/// The exception context as it is stored on the stack on exception entry. -#[repr(C)] -struct ExceptionContext { - /// General Purpose Registers. - gpr: [u64; 30], - - /// The link register, aka x30. - lr: u64, - - /// Exception link register. The program counter at the time the exception happened. - elr_el1: u64, - - /// Saved program status. - spsr_el1: SpsrEL1, -} - -/// Wrapper struct for pretty printing ESR_EL1. -struct EsrEL1; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Prints verbose information about the exception and then panics. -fn default_exception_handler(e: &ExceptionContext) { - panic!( - "\n\nCPU Exception!\n\ - FAR_EL1: {:#018x}\n\ - {}\n\ - {}", - FAR_EL1.get(), - EsrEL1 {}, - e - ); -} - -//------------------------------------------------------------------------------ -// Current, EL0 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn current_el0_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_el0_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_el0_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Current, ELx -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { - use exception::asynchronous::interface::IRQManager; - - let token = &exception::asynchronous::IRQContext::new(); - bsp::exception::asynchronous::irq_manager().handle_pending_irqs(token); -} - -#[no_mangle] -unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Lower, AArch64 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Lower, AArch32 -//------------------------------------------------------------------------------ - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -#[no_mangle] -unsafe extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { - default_exception_handler(e); -} - -//------------------------------------------------------------------------------ -// Pretty printing -//------------------------------------------------------------------------------ - -/// Human readable ESR_EL1. -#[rustfmt::skip] -impl fmt::Display for EsrEL1 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let esr_el1 = ESR_EL1.extract(); - - // Raw print of whole register. - writeln!(f, "ESR_EL1: {:#010x}", esr_el1.get())?; - - // Raw print of exception class. - write!(f, " Exception Class (EC) : {:#x}", esr_el1.read(ESR_EL1::EC))?; - - // Exception class, translation. - let ec_translation = match esr_el1.read_as_enum(ESR_EL1::EC) { - Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", - _ => "N/A", - }; - writeln!(f, " - {}", ec_translation)?; - - // Raw print of instruction specific syndrome. - write!(f, " Instr Specific Syndrome (ISS): {:#x}", esr_el1.read(ESR_EL1::ISS))?; - - Ok(()) - } -} - -/// Human readable SPSR_EL1. -#[rustfmt::skip] -impl fmt::Display for SpsrEL1 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Raw value. - writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; - - let to_flag_str = |x| -> _ { - if x { "Set" } else { "Not set" } - }; - - writeln!(f, " Flags:")?; - writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; - writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; - writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; - writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - writeln!(f, " Exception handling state:")?; - writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; - writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; - writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; - writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; - - write!(f, " Illegal Execution State (IL): {}", - to_flag_str(self.0.is_set(SPSR_EL1::IL)) - )?; - - Ok(()) - } -} - -/// Human readable print of the exception context. -impl fmt::Display for ExceptionContext { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; - writeln!(f, "{}", self.spsr_el1)?; - writeln!(f)?; - writeln!(f, "General purpose register:")?; - - #[rustfmt::skip] - let alternating = |x| -> _ { - if x % 2 == 0 { " " } else { "\n" } - }; - - // Print two registers per line. - for (i, reg) in self.gpr.iter().enumerate() { - write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; - } - write!(f, " lr : {:#018x}", self.lr)?; - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use crate::exception::PrivilegeLevel; - -/// The processing element's current privilege level. -pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { - let el = CurrentEL.read_as_enum(CurrentEL::EL); - match el { - Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), - Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), - Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), - _ => (PrivilegeLevel::Unknown, "Unknown"), - } -} - -/// Init exception handling by setting the exception vector base address register. -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must -/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference -/// Manual. -pub unsafe fn handling_init() { - // Provided by exception.S. - extern "Rust" { - static __exception_vector_start: UnsafeCell<()>; - } - - VBAR_EL1.set(__exception_vector_start.get() as u64); - - // Force VBAR update to complete before next instruction. - barrier::isb(barrier::SY); -} diff --git a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception/asynchronous.rs b/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception/asynchronous.rs deleted file mode 100644 index df6a5c3f7..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception/asynchronous.rs +++ /dev/null @@ -1,143 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural asynchronous exception handling. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -mod daif_bits { - pub const IRQ: u8 = 0b0010; -} - -trait DaifField { - fn daif_field() -> register::Field; -} - -struct Debug; -struct SError; -struct IRQ; -struct FIQ; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl DaifField for Debug { - fn daif_field() -> register::Field { - DAIF::D - } -} - -impl DaifField for SError { - fn daif_field() -> register::Field { - DAIF::A - } -} - -impl DaifField for IRQ { - fn daif_field() -> register::Field { - DAIF::I - } -} - -impl DaifField for FIQ { - fn daif_field() -> register::Field { - DAIF::F - } -} - -fn is_masked() -> bool -where - T: DaifField, -{ - DAIF.is_set(T::daif_field()) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Returns whether IRQs are masked on the executing core. -pub fn is_local_irq_masked() -> bool { - !is_masked::() -} - -/// Unmask IRQs on the executing core. -/// -/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. -/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: -/// -/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional -/// synchronization." -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -#[inline(always)] -pub unsafe fn local_irq_unmask() { - #[rustfmt::skip] - asm!( - "msr DAIFClr, {arg}", - arg = const daif_bits::IRQ, - options(nomem, nostack, preserves_flags) - ); -} - -/// Mask IRQs on the executing core. -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -#[inline(always)] -pub unsafe fn local_irq_mask() { - #[rustfmt::skip] - asm!( - "msr DAIFSet, {arg}", - arg = const daif_bits::IRQ, - options(nomem, nostack, preserves_flags) - ); -} - -/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -#[inline(always)] -pub unsafe fn local_irq_mask_save() -> u64 { - let saved = DAIF.get(); - local_irq_mask(); - - saved -} - -/// Restore the interrupt mask bits (DAIF) using the callee's argument. -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. -/// - No sanity checks on the input. -#[inline(always)] -pub unsafe fn local_irq_restore(saved: u64) { - DAIF.set(saved); -} - -/// Print the AArch64 exceptions status. -#[rustfmt::skip] -pub fn print_state() { - use crate::info; - - let to_mask_str = |x| -> _ { - if x { "Masked" } else { "Unmasked" } - }; - - info!(" Debug: {}", to_mask_str(is_masked::())); - info!(" SError: {}", to_mask_str(is_masked::())); - info!(" IRQ: {}", to_mask_str(is_masked::())); - info!(" FIQ: {}", to_mask_str(is_masked::())); -} diff --git a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs b/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs deleted file mode 100644 index cf0989bef..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs +++ /dev/null @@ -1,554 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management Unit Driver. -//! -//! Only 64 KiB granule is supported. - -use crate::{ - bsp, - memory::{ - mmu, - mmu::{ - AccessPermissions, Address, AddressType, AttributeFields, MemAttributes, Page, - PageSliceDescriptor, Physical, Virtual, - }, - }, - synchronization::InitStateLock, -}; -use core::convert; -use cortex_a::{barrier, regs::*}; -use register::{register_bitfields, InMemoryRegister}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- -use mmu::interface::TranslationGranule; - -// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. -register_bitfields! {u64, - STAGE1_TABLE_DESCRIPTOR [ - /// Physical address of the next descriptor. - NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. -register_bitfields! {u64, - STAGE1_PAGE_DESCRIPTOR [ - /// Privileged execute-never. - PXN OFFSET(53) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). - OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] - - /// Access flag. - AF OFFSET(10) NUMBITS(1) [ - False = 0, - True = 1 - ], - - /// Shareability field. - SH OFFSET(8) NUMBITS(2) [ - OuterShareable = 0b10, - InnerShareable = 0b11 - ], - - /// Access Permissions. - AP OFFSET(6) NUMBITS(2) [ - RW_EL1 = 0b00, - RW_EL1_EL0 = 0b01, - RO_EL1 = 0b10, - RO_EL1_EL0 = 0b11 - ], - - /// Memory attributes index into the MAIR_EL1 register. - AttrIndx OFFSET(2) NUMBITS(3) [], - - TYPE OFFSET(1) NUMBITS(1) [ - Block = 0, - Table = 1 - ], - - VALID OFFSET(0) NUMBITS(1) [ - False = 0, - True = 1 - ] - ] -} - -/// A table descriptor for 64 KiB aperture. -/// -/// The output points to the next table. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct TableDescriptor(u64); - -/// A page descriptor with 64 KiB aperture. -/// -/// The output points to physical memory. -#[derive(Copy, Clone)] -#[repr(transparent)] -struct PageDescriptor(u64); - -#[derive(Copy, Clone)] -enum Granule512MiB {} - -trait BaseAddr { - fn phys_base_addr(&self) -> Address; -} - -/// Constants for indexing the MAIR_EL1. -#[allow(dead_code)] -mod mair { - pub const DEVICE: u64 = 0; - pub const NORMAL: u64 = 1; -} - -/// Memory Management Unit type. -struct MemoryManagementUnit; - -/// This constant is the power-of-two exponent that defines the virtual address space size. -/// -/// Values tested and known to be working: -/// - 30 (1 GiB) -/// - 31 (2 GiB) -/// - 32 (4 GiB) -/// - 33 (8 GiB) -const ADDR_SPACE_SIZE_EXPONENT: usize = 33; - -const NUM_LVL2_TABLES: usize = (1 << ADDR_SPACE_SIZE_EXPONENT) >> Granule512MiB::SHIFT; -const T0SZ: u64 = (64 - ADDR_SPACE_SIZE_EXPONENT) as u64; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB -/// aligned, hence the "reverse" order of appearance. -#[repr(C)] -#[repr(align(65536))] -pub(in crate::memory::mmu) struct FixedSizeTranslationTable { - /// Page descriptors, covering 64 KiB windows per entry. - lvl3: [[PageDescriptor; 8192]; NUM_TABLES], - - /// Table descriptors, covering 512 MiB windows. - lvl2: [TableDescriptor; NUM_TABLES], - - /// Index of the next free MMIO page. - cur_l3_mmio_index: usize, - - /// Have the tables been initialized? - initialized: bool, -} - -pub(in crate::memory::mmu) type ArchTranslationTable = FixedSizeTranslationTable; - -// Supported translation granules are exported below, so that BSP code can pick between the options. -// This driver only supports 64 KiB at the moment. - -#[derive(Copy, Clone)] -/// 64 KiB translation granule. -pub enum Granule64KiB {} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -/// The translation tables. -/// -/// # Safety -/// -/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". -static KERNEL_TABLES: InitStateLock = - InitStateLock::new(ArchTranslationTable::new()); - -static MMU: MemoryManagementUnit = MemoryManagementUnit; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl mmu::interface::TranslationGranule for Granule512MiB { - const SIZE: usize = 512 * 1024 * 1024; - const SHIFT: usize = 29; // log2(SIZE) -} - -impl BaseAddr for [T; N] { - fn phys_base_addr(&self) -> Address { - // The binary is still identity mapped, so we don't need to convert here. - Address::new(self as *const _ as usize) - } -} - -impl convert::From for TableDescriptor { - fn from(next_lvl_table_addr: usize) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = next_lvl_table_addr >> Granule64KiB::SHIFT; - val.write( - STAGE1_TABLE_DESCRIPTOR::VALID::True - + STAGE1_TABLE_DESCRIPTOR::TYPE::Table - + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64), - ); - - TableDescriptor(val.get()) - } -} - -/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. -impl convert::From - for register::FieldValue -{ - fn from(attribute_fields: AttributeFields) -> Self { - // Memory attributes. - let mut desc = match attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => { - STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::NORMAL) - } - MemAttributes::Device => { - STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable - + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(mair::DEVICE) - } - }; - - // Access Permissions. - desc += match attribute_fields.acc_perms { - AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, - AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, - }; - - // Execute Never. - desc += if attribute_fields.execute_never { - STAGE1_PAGE_DESCRIPTOR::PXN::True - } else { - STAGE1_PAGE_DESCRIPTOR::PXN::False - }; - - desc - } -} - -impl PageDescriptor { - /// Create an instance. - fn new(output_addr: *const Page, attribute_fields: &AttributeFields) -> Self { - let val = InMemoryRegister::::new(0); - - let shifted = output_addr as u64 >> Granule64KiB::SHIFT; - val.write( - STAGE1_PAGE_DESCRIPTOR::VALID::True - + STAGE1_PAGE_DESCRIPTOR::AF::True - + attribute_fields.clone().into() - + STAGE1_PAGE_DESCRIPTOR::TYPE::Table - + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted), - ); - - Self(val.get()) - } - - /// Returns the valid bit. - fn is_valid(&self) -> bool { - InMemoryRegister::::new(self.0) - .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) - } -} - -impl FixedSizeTranslationTable<{ NUM_TABLES }> { - // Reserve the last 256 MiB of the address space for MMIO mappings. - const L2_MMIO_START_INDEX: usize = NUM_TABLES - 1; - const L3_MMIO_START_INDEX: usize = 8192 / 2; - - /// Create an instance. - pub const fn new() -> Self { - assert!(NUM_TABLES > 0); - - Self { - lvl3: [[PageDescriptor(0); 8192]; NUM_TABLES], - lvl2: [TableDescriptor(0); NUM_TABLES], - cur_l3_mmio_index: 0, - initialized: false, - } - } - - /// The start address of the table's MMIO range. - #[inline(always)] - fn mmio_start_addr(&self) -> Address { - Address::new( - (Self::L2_MMIO_START_INDEX << Granule512MiB::SHIFT) - | (Self::L3_MMIO_START_INDEX << Granule64KiB::SHIFT), - ) - } - - /// The inclusive end address of the table's MMIO range. - #[inline(always)] - fn mmio_end_addr_inclusive(&self) -> Address { - Address::new( - (Self::L2_MMIO_START_INDEX << Granule512MiB::SHIFT) - | (8191 << Granule64KiB::SHIFT) - | (Granule64KiB::SIZE - 1), - ) - } - - /// Helper to calculate the lvl2 and lvl3 indices from an address. - #[inline(always)] - fn lvl2_lvl3_index_from( - &self, - addr: *const Page, - ) -> Result<(usize, usize), &'static str> { - let lvl2_index = addr as usize >> Granule512MiB::SHIFT; - let lvl3_index = (addr as usize & Granule512MiB::MASK) >> Granule64KiB::SHIFT; - - if lvl2_index > (NUM_TABLES - 1) { - return Err("Virtual page is out of bounds of translation table"); - } - - Ok((lvl2_index, lvl3_index)) - } - - /// Returns the PageDescriptor corresponding to the supplied Page. - #[inline(always)] - fn page_descriptor_from( - &mut self, - addr: *const Page, - ) -> Result<&mut PageDescriptor, &'static str> { - let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from(addr)?; - - Ok(&mut self.lvl3[lvl2_index][lvl3_index]) - } -} - -/// Setup function for the MAIR_EL1 register. -fn set_up_mair() { - // Define the memory types being mapped. - MAIR_EL1.write( - // Attribute 1 - Cacheable normal DRAM. - MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + - MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + - - // Attribute 0 - Device. - MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, - ); -} - -/// Configure various settings of stage 1 of the EL1 translation regime. -fn configure_translation_control() { - let ips = ID_AA64MMFR0_EL1.read(ID_AA64MMFR0_EL1::PARange); - - TCR_EL1.write( - TCR_EL1::TBI0::Ignored - + TCR_EL1::IPS.val(ips) - + TCR_EL1::TG0::KiB_64 - + TCR_EL1::SH0::Inner - + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::EPD0::EnableTTBR0Walks - + TCR_EL1::T0SZ.val(T0SZ), - ); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a guarded reference to the kernel's translation tables. -pub(in crate::memory::mmu) fn kernel_translation_tables( -) -> &'static InitStateLock { - &KERNEL_TABLES -} - -/// Return a reference to the MMU instance. -pub(in crate::memory::mmu) fn mmu() -> &'static impl mmu::interface::MMU { - &MMU -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -impl mmu::interface::TranslationGranule for Granule64KiB { - const SIZE: usize = 64 * 1024; - const SHIFT: usize = 16; // log2(SIZE) -} - -impl mmu::interface::TranslationTable - for FixedSizeTranslationTable<{ NUM_TABLES }> -{ - unsafe fn init(&mut self) { - if self.initialized { - return; - } - - // Populate the l2 entries. - for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { - *lvl2_entry = self.lvl3[lvl2_nr].phys_base_addr().into_usize().into(); - } - - self.cur_l3_mmio_index = Self::L3_MMIO_START_INDEX; - self.initialized = true; - } - - fn phys_base_address(&self) -> Address { - self.lvl2.phys_base_addr() - } - - unsafe fn map_pages_at( - &mut self, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, - ) -> Result<(), &'static str> { - assert_eq!(self.initialized, true, "Translation tables not initialized"); - - let p = phys_pages.as_slice(); - let v = virt_pages.as_slice(); - - if p.len() != v.len() { - return Err("Tried to map page slices with unequal sizes"); - } - - // No work to do for empty slices. - if p.is_empty() { - return Ok(()); - } - - if p.last().unwrap().as_ptr() >= bsp::memory::mmu::phys_addr_space_end_page() { - return Err("Tried to map outside of physical address space"); - } - - let iter = p.iter().zip(v.iter()); - for (phys_page, virt_page) in iter { - let page_descriptor = self.page_descriptor_from(virt_page.as_ptr())?; - if page_descriptor.is_valid() { - return Err("Virtual page is already mapped"); - } - - *page_descriptor = PageDescriptor::new(phys_page.as_ptr(), &attr); - } - - Ok(()) - } - - fn next_mmio_virt_page_slice( - &mut self, - num_pages: usize, - ) -> Result, &'static str> { - assert_eq!(self.initialized, true, "Translation tables not initialized"); - - if num_pages == 0 { - return Err("num_pages == 0"); - } - - if (self.cur_l3_mmio_index + num_pages) > 8191 { - return Err("Not enough MMIO space left"); - } - - let addr = (Self::L2_MMIO_START_INDEX << Granule512MiB::SHIFT) - | (self.cur_l3_mmio_index << Granule64KiB::SHIFT); - self.cur_l3_mmio_index += num_pages; - - Ok(PageSliceDescriptor::from_addr( - Address::new(addr), - num_pages, - )) - } - - fn is_virt_page_slice_mmio(&self, virt_pages: &PageSliceDescriptor) -> bool { - let start_addr = virt_pages.start_addr(); - let end_addr_inclusive = virt_pages.end_addr_inclusive(); - - for i in [start_addr, end_addr_inclusive].iter() { - if (*i >= self.mmio_start_addr()) && (*i <= self.mmio_end_addr_inclusive()) { - return true; - } - } - - false - } -} - -impl mmu::interface::MMU for MemoryManagementUnit { - unsafe fn enable( - &self, - phys_kernel_table_base_addr: Address, - ) -> Result<(), &'static str> { - // Fail early if translation granule is not supported. Both RPis support it, though. - if !ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported) { - return Err("Translation granule not supported in HW"); - } - - // Prepare the memory attribute indirection register. - set_up_mair(); - - // Set the "Translation Table Base Register". - TTBR0_EL1.set_baddr(phys_kernel_table_base_addr.into_usize() as u64); - - configure_translation_control(); - - // Switch the MMU on. - // - // First, force all previous changes to be seen before the MMU is enabled. - barrier::isb(barrier::SY); - - // Enable the MMU and turn on data and instruction caching. - SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); - - // Force MMU init to complete before next instruction. - barrier::isb(barrier::SY); - - Ok(()) - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -pub(in crate::memory::mmu) type MinSizeArchTranslationTable = FixedSizeTranslationTable<1>; - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check if the size of `struct TableDescriptor` is as expected. - #[kernel_test] - fn size_of_tabledescriptor_equals_64_bit() { - assert_eq!( - core::mem::size_of::(), - core::mem::size_of::() - ); - } - - /// Check if the size of `struct PageDescriptor` is as expected. - #[kernel_test] - fn size_of_pagedescriptor_equals_64_bit() { - assert_eq!( - core::mem::size_of::(), - core::mem::size_of::() - ); - } - - /// Check if KERNEL_TABLES is in .bss. - #[kernel_test] - fn kernel_tables_in_bss() { - let bss_range = bsp::memory::bss_range_inclusive(); - let kernel_tables_addr = &KERNEL_TABLES as *const _ as usize as *mut u64; - - assert!(bss_range.contains(&kernel_tables_addr)); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs b/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs deleted file mode 100644 index e9b0234db..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) - } - - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; - - Duration::from_nanos(current_count / frq) - } - - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } - - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get(); - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; - } - - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); - - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); - - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} - - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp.rs b/15_virtual_mem_part2_mmio_remap/src/bsp.rs deleted file mode 100644 index 3a5657ade..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Conditional re-exporting of Board Support Packages. - -mod device_driver; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod raspberrypi; - -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use raspberrypi::*; diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver.rs deleted file mode 100644 index 3fe1fa555..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver.rs +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Device driver. - -#[cfg(feature = "bsp_rpi4")] -mod arm; -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -mod bcm; -mod common; - -#[cfg(feature = "bsp_rpi4")] -pub use arm::*; -#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] -pub use bcm::*; diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm.rs deleted file mode 100644 index 6d9d3bdf0..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! ARM driver top level. - -pub mod gicv2; - -pub use gicv2::*; diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs deleted file mode 100644 index 9b23af353..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs +++ /dev/null @@ -1,251 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! GICv2 Driver - ARM Generic Interrupt Controller v2. -//! -//! The following is a collection of excerpts with useful information from -//! - `Programmer's Guide for ARMv8-A` -//! - `ARM Generic Interrupt Controller Architecture Specification` -//! -//! # Programmer's Guide - 10.6.1 Configuration -//! -//! The GIC is accessed as a memory-mapped peripheral. -//! -//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core -//! uses the same address to access its own private CPU interface. -//! -//! It is not possible for a core to access the CPU interface of another core. -//! -//! # Architecture Specification - 10.6.2 Initialization -//! -//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized -//! after reset before it can deliver interrupts to the core. -//! -//! In the Distributor, software must configure the priority, target, security and enable individual -//! interrupts. The Distributor must subsequently be enabled through its control register -//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption -//! settings. -//! -//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This -//! prepares the GIC to deliver interrupts to the core. -//! -//! Before interrupts are expected in the core, software prepares the core to take interrupts by -//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in -//! PSTATE, and setting the routing controls. -//! -//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. -//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. -//! Individual interrupts can also be disabled (or enabled) in the distributor. -//! -//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must -//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the -//! core's priority mask. -//! -//! # Architecture Specification - 1.4.2 Interrupt types -//! -//! - Peripheral interrupt -//! - Private Peripheral Interrupt (PPI) -//! - This is a peripheral interrupt that is specific to a single processor. -//! - Shared Peripheral Interrupt (SPI) -//! - This is a peripheral interrupt that the Distributor can route to any of a specified -//! combination of processors. -//! -//! - Software-generated interrupt (SGI) -//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The -//! system uses SGIs for interprocessor communication. -//! - An SGI has edge-triggered properties. The software triggering of the interrupt is -//! equivalent to the edge transition of the interrupt request signal. -//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt -//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, -//! identifies the processor that requested the interrupt. -//! -//! # Architecture Specification - 2.2.1 Interrupt IDs -//! -//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 -//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by -//! the Distributor. -//! -//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: -//! - Interrupt numbers 32..1019 are used for SPIs. -//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These -//! interrupts are banked in the Distributor. -//! - A banked interrupt is one where the Distributor can have multiple interrupts with the -//! same ID. A banked interrupt is identified uniquely by its ID number and its associated -//! CPU interface number. Of the banked interrupt IDs: -//! - 00..15 SGIs -//! - 16..31 PPIs - -mod gicc; -mod gicd; - -use crate::{ - bsp, cpu, driver, exception, memory, memory::mmu::Physical, synchronization, - synchronization::InitStateLock, -}; -use core::sync::atomic::{AtomicBool, Ordering}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -type HandlerTable = [Option; GICv2::NUM_IRQS]; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; - -/// Representation of the GIC. -pub struct GICv2 { - gicd_phys_mmio_descriptor: memory::mmu::MMIODescriptor, - gicc_phys_mmio_descriptor: memory::mmu::MMIODescriptor, - - /// The Distributor. - gicd: gicd::GICD, - - /// The CPU Interface. - gicc: gicc::GICC, - - /// Have the MMIO regions been remapped yet? - is_mmio_remapped: AtomicBool, - - /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. - handler_table: InitStateLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GICv2 { - const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. - const NUM_IRQS: usize = Self::MAX_IRQ_NUMBER + 1; - - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new( - gicd_phys_mmio_descriptor: memory::mmu::MMIODescriptor, - gicc_phys_mmio_descriptor: memory::mmu::MMIODescriptor, - ) -> Self { - Self { - gicd_phys_mmio_descriptor, - gicc_phys_mmio_descriptor, - gicd: gicd::GICD::new(gicd_phys_mmio_descriptor.start_addr().into_usize()), - gicc: gicc::GICC::new(gicc_phys_mmio_descriptor.start_addr().into_usize()), - is_mmio_remapped: AtomicBool::new(false), - handler_table: InitStateLock::new([None; Self::NUM_IRQS]), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::ReadWriteEx; - -impl driver::interface::DeviceDriver for GICv2 { - fn compatible(&self) -> &'static str { - "GICv2 (ARM Generic Interrupt Controller v2)" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - let remapped = self.is_mmio_remapped.load(Ordering::Relaxed); - if !remapped { - let mut virt_addr; - - // GICD - virt_addr = memory::mmu::kernel_map_mmio("GICD", &self.gicd_phys_mmio_descriptor)?; - self.gicd.set_mmio(virt_addr.into_usize()); - - // GICC - virt_addr = memory::mmu::kernel_map_mmio("GICC", &self.gicc_phys_mmio_descriptor)?; - self.gicc.set_mmio(virt_addr.into_usize()); - - // Conclude remapping. - self.is_mmio_remapped.store(true, Ordering::Relaxed); - } - - if cpu::smp::core_id::() == bsp::cpu::BOOT_CORE_ID { - self.gicd.boot_core_init(); - } - - self.gicc.priority_accept_all(); - self.gicc.enable(); - - Ok(()) - } -} - -impl exception::asynchronous::interface::IRQManager for GICv2 { - type IRQNumberType = IRQNumber; - - fn register_handler( - &self, - irq_number: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, - ) -> Result<(), &'static str> { - self.handler_table.write(|table| { - let irq_number = irq_number.get(); - - if table[irq_number].is_some() { - return Err("IRQ handler already registered"); - } - - table[irq_number] = Some(descriptor); - - Ok(()) - }) - } - - fn enable(&self, irq_number: Self::IRQNumberType) { - self.gicd.enable(irq_number); - } - - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { - // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register - // (IAR). - let irq_number = self.gicc.pending_irq_number(ic); - - // Guard against spurious interrupts. - if irq_number > GICv2::MAX_IRQ_NUMBER { - return; - } - - // Call the IRQ handler. Panic if there is none. - self.handler_table.read(|table| { - match table[irq_number] { - None => panic!("No handler registered for IRQ {}", irq_number), - Some(descriptor) => { - // Call the IRQ handler. Panics on failure. - descriptor.handler.handle().expect("Error handling IRQ"); - } - } - }); - - // Signal completion of handling. - self.gicc.mark_comleted(irq_number as u32, ic); - } - - fn print_handler(&self) { - use crate::info; - - info!(" Peripheral handler:"); - - self.handler_table.read(|table| { - for (i, opt) in table.iter().skip(32).enumerate() { - if let Some(handler) = opt { - info!(" {: >3}. {}", i + 32, handler.name); - } - } - }); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs deleted file mode 100644 index ee1b64087..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs +++ /dev/null @@ -1,152 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! GICC Driver - GIC CPU interface. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, exception, synchronization::InitStateLock, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -register_bitfields! { - u32, - - /// CPU Interface Control Register - CTLR [ - Enable OFFSET(0) NUMBITS(1) [] - ], - - /// Interrupt Priority Mask Register - PMR [ - Priority OFFSET(0) NUMBITS(8) [] - ], - - /// Interrupt Acknowledge Register - IAR [ - InterruptID OFFSET(0) NUMBITS(10) [] - ], - - /// End of Interrupt Register - EOIR [ - EOIINTID OFFSET(0) NUMBITS(10) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x000 => CTLR: ReadWrite), - (0x004 => PMR: ReadWrite), - (0x008 => _reserved1), - (0x00C => IAR: ReadWrite), - (0x010 => EOIR: ReadWrite), - (0x014 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Representation of the GIC CPU interface. -pub struct GICC { - registers: InitStateLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use crate::synchronization::interface::ReadWriteEx; - -impl GICC { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: InitStateLock::new(Registers::new(mmio_start_addr)), - } - } - - pub unsafe fn set_mmio(&self, new_mmio_start_addr: usize) { - self.registers - .write(|regs| *regs = Registers::new(new_mmio_start_addr)); - } - - /// Accept interrupts of any priority. - /// - /// Quoting the GICv2 Architecture Specification: - /// - /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field - /// value." - /// - /// # Safety - /// - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - pub fn priority_accept_all(&self) { - self.registers.read(|regs| { - regs.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. - }); - } - - /// Enable the interface - start accepting IRQs. - /// - /// # Safety - /// - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - pub fn enable(&self) { - self.registers.read(|regs| { - regs.CTLR.write(CTLR::Enable::SET); - }); - } - - /// Extract the number of the highest-priority pending IRQ. - /// - /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. - /// - /// # Safety - /// - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - #[allow(clippy::trivially_copy_pass_by_ref)] - pub fn pending_irq_number<'irq_context>( - &self, - _ic: &exception::asynchronous::IRQContext<'irq_context>, - ) -> usize { - self.registers - .read(|regs| regs.IAR.read(IAR::InterruptID) as usize) - } - - /// Complete handling of the currently active IRQ. - /// - /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. - /// - /// To be called after `pending_irq_number()`. - /// - /// # Safety - /// - /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead - /// of `&mut self`. - #[allow(clippy::trivially_copy_pass_by_ref)] - pub fn mark_comleted<'irq_context>( - &self, - irq_number: u32, - _ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { - self.registers.read(|regs| { - regs.EOIR.write(EOIR::EOIINTID.val(irq_number)); - }); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicd.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicd.rs deleted file mode 100644 index f221e7246..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicd.rs +++ /dev/null @@ -1,205 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! GICD Driver - GIC Distributor. -//! -//! # Glossary -//! - SPI - Shared Peripheral Interrupt. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, - state, synchronization, - synchronization::{IRQSafeNullLock, InitStateLock}, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -register_bitfields! { - u32, - - /// Distributor Control Register - CTLR [ - Enable OFFSET(0) NUMBITS(1) [] - ], - - /// Interrupt Controller Type Register - TYPER [ - ITLinesNumber OFFSET(0) NUMBITS(5) [] - ], - - /// Interrupt Processor Targets Registers - ITARGETSR [ - Offset3 OFFSET(24) NUMBITS(8) [], - Offset2 OFFSET(16) NUMBITS(8) [], - Offset1 OFFSET(8) NUMBITS(8) [], - Offset0 OFFSET(0) NUMBITS(8) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - SharedRegisterBlock { - (0x000 => CTLR: ReadWrite), - (0x004 => TYPER: ReadOnly), - (0x008 => _reserved1), - (0x104 => ISENABLER: [ReadWrite; 31]), - (0x108 => _reserved2), - (0x820 => ITARGETSR: [ReadWrite; 248]), - (0x824 => @END), - } -} - -register_structs! { - #[allow(non_snake_case)] - BankedRegisterBlock { - (0x000 => _reserved1), - (0x100 => ISENABLER: ReadWrite), - (0x104 => _reserved2), - (0x800 => ITARGETSR: [ReadOnly; 8]), - (0x804 => @END), - } -} - -/// Abstraction for the non-banked parts of the associated MMIO registers. -type SharedRegisters = MMIODerefWrapper; - -/// Abstraction for the banked parts of the associated MMIO registers. -type BankedRegisters = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Representation of the GIC Distributor. -pub struct GICD { - /// Access to shared registers is guarded with a lock. - shared_registers: IRQSafeNullLock, - - /// Access to banked registers is unguarded. - banked_registers: InitStateLock, -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl SharedRegisters { - /// Return the number of IRQs that this HW implements. - #[inline(always)] - fn num_irqs(&mut self) -> usize { - // Query number of implemented IRQs. - // - // Refer to GICv2 Architecture Specification, Section 4.3.2. - ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 - } - - /// Return a slice of the implemented ITARGETSR. - #[inline(always)] - fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { - assert!(self.num_irqs() >= 36); - - // Calculate the max index of the shared ITARGETSR array. - // - // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS - // register has four entries, so shift right by two. Subtract one because we start - // counting at zero. - let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; - - // Rust automatically inserts slice range sanity check, i.e. max >= min. - &self.ITARGETSR[0..spi_itargetsr_max_index] - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use crate::synchronization::interface::ReadWriteEx; -use synchronization::interface::Mutex; - -impl GICD { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), - banked_registers: InitStateLock::new(BankedRegisters::new(mmio_start_addr)), - } - } - - pub unsafe fn set_mmio(&self, new_mmio_start_addr: usize) { - self.shared_registers - .lock(|regs| *regs = SharedRegisters::new(new_mmio_start_addr)); - self.banked_registers - .write(|regs| *regs = BankedRegisters::new(new_mmio_start_addr)); - } - - /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. - /// - /// Quoting the GICv2 Architecture Specification: - /// - /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that - /// corresponds only to the processor reading the register." - fn local_gic_target_mask(&self) -> u32 { - self.banked_registers - .read(|regs| regs.ITARGETSR[0].read(ITARGETSR::Offset0)) - } - - /// Route all SPIs to the boot core and enable the distributor. - pub fn boot_core_init(&self) { - assert!( - state::state_manager().is_init(), - "Only allowed during kernel init phase" - ); - - // Target all SPIs to the boot core only. - let mask = self.local_gic_target_mask(); - - self.shared_registers.lock(|regs| { - for i in regs.implemented_itargets_slice().iter() { - i.write( - ITARGETSR::Offset3.val(mask) - + ITARGETSR::Offset2.val(mask) - + ITARGETSR::Offset1.val(mask) - + ITARGETSR::Offset0.val(mask), - ); - } - - regs.CTLR.write(CTLR::Enable::SET); - }); - } - - /// Enable an interrupt. - pub fn enable(&self, irq_num: super::IRQNumber) { - let irq_num = irq_num.get(); - - // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 - // (division by 32) and arrive at the index for the respective ISENABLER[i]. - let enable_reg_index = irq_num >> 5; - let enable_bit: u32 = 1u32 << (irq_num % 32); - - // Check if we are handling a private or shared IRQ. - match irq_num { - // Private. - 0..=31 => self.banked_registers.read(|regs| { - let enable_reg = ®s.ISENABLER; - enable_reg.set(enable_reg.get() | enable_bit); - }), - // Shared. - _ => { - let enable_reg_index_shared = enable_reg_index - 1; - - self.shared_registers.lock(|regs| { - let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; - enable_reg.set(enable_reg.get() | enable_bit); - }); - } - } - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm.rs deleted file mode 100644 index 5e4c9e705..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm.rs +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BCM driver top level. - -mod bcm2xxx_gpio; -#[cfg(feature = "bsp_rpi3")] -mod bcm2xxx_interrupt_controller; -mod bcm2xxx_pl011_uart; - -pub use bcm2xxx_gpio::*; -#[cfg(feature = "bsp_rpi3")] -pub use bcm2xxx_interrupt_controller::*; -pub use bcm2xxx_pl011_uart::*; diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index 680ad4cb9..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,258 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, memory, memory::mmu::Physical, - synchronization, synchronization::IRQSafeNullLock, -}; -use core::sync::atomic::{AtomicUsize, Ordering}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// GPIO registers. -// -// Descriptions taken from -// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf -register_bitfields! { - u32, - - /// GPIO Function Select 1 - GPFSEL1 [ - /// Pin 15 - FSEL15 OFFSET(15) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART RX - - ], - - /// Pin 14 - FSEL14 OFFSET(12) NUMBITS(3) [ - Input = 0b000, - Output = 0b001, - AltFunc0 = 0b100 // PL011 UART TX - ] - ], - - /// GPIO Pull-up/down Register - /// - /// BCM2837 only. - GPPUD [ - /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. - PUD OFFSET(0) NUMBITS(2) [ - Off = 0b00, - PullDown = 0b01, - PullUp = 0b10 - ] - ], - - /// GPIO Pull-up/down Clock Register 0 - /// - /// BCM2837 only. - GPPUDCLK0 [ - /// Pin 15 - PUDCLK15 OFFSET(15) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ], - - /// Pin 14 - PUDCLK14 OFFSET(14) NUMBITS(1) [ - NoEffect = 0, - AssertClock = 1 - ] - ], - - /// GPIO Pull-up / Pull-down Register 0 - /// - /// BCM2711 only. - GPIO_PUP_PDN_CNTRL_REG0 [ - /// Pin 15 - GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ], - - /// Pin 14 - GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ - NoResistor = 0b00, - PullUp = 0b01 - ] - ] -} - -register_structs! { - #[allow(non_snake_case)] - RegisterBlock { - (0x00 => _reserved1), - (0x04 => GPFSEL1: ReadWrite), - (0x08 => _reserved2), - (0x94 => GPPUD: ReadWrite), - (0x98 => GPPUDCLK0: ReadWrite), - (0x9C => _reserved3), - (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), - (0xE8 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { - registers: Registers, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; - -/// Representation of the GPIO HW. -pub struct GPIO { - phys_mmio_descriptor: memory::mmu::MMIODescriptor, - virt_mmio_start_addr: AtomicUsize, - inner: IRQSafeNullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl GPIOInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - } - } - - /// Init code. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub unsafe fn init(&mut self, new_mmio_start_addr: Option) -> Result<(), &'static str> { - if let Some(addr) = new_mmio_start_addr { - self.registers = Registers::new(addr); - } - - Ok(()) - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; - use core::time::Duration; - - // The Linux 2837 GPIO driver waits 1 µs between the steps. - const DELAY: Duration = Duration::from_micros(1); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - time::time_manager().spin_for(DELAY); - - self.registers - .GPPUDCLK0 - .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - time::time_manager().spin_for(DELAY); - - self.registers.GPPUD.write(GPPUD::PUD::Off); - self.registers.GPPUDCLK0.set(0); - } - - /// Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi4")] - fn disable_pud_14_15_bcm2711(&mut self) { - self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( - GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp - + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, - ); - } - - /// Map PL011 UART as standard output. - /// - /// TX to pin 14 - /// RX to pin 15 - pub fn map_pl011_uart(&mut self) { - // Select the UART on pins 14 and 15. - self.registers - .GPFSEL1 - .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); - - // Disable pull-up/down on pins 14 and 15. - #[cfg(feature = "bsp_rpi3")] - self.disable_pud_14_15_bcm2837(); - - #[cfg(feature = "bsp_rpi4")] - self.disable_pud_14_15_bcm2711(); - } -} - -impl GPIO { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new(phys_mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { - Self { - phys_mmio_descriptor, - virt_mmio_start_addr: AtomicUsize::new(0), - inner: IRQSafeNullLock::new(GPIOInner::new( - phys_mmio_descriptor.start_addr().into_usize(), - )), - } - } - - /// Concurrency safe version of `GPIOInner.map_pl011_uart()` - pub fn map_pl011_uart(&self) { - self.inner.lock(|inner| inner.map_pl011_uart()) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for GPIO { - fn compatible(&self) -> &'static str { - "BCM GPIO" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - let virt_addr = - memory::mmu::kernel_map_mmio(self.compatible(), &self.phys_mmio_descriptor)?; - - self.inner - .lock(|inner| inner.init(Some(virt_addr.into_usize())))?; - - self.virt_mmio_start_addr - .store(virt_addr.into_usize(), Ordering::Relaxed); - - Ok(()) - } - - fn virt_mmio_start_addr(&self) -> Option { - let addr = self.virt_mmio_start_addr.load(Ordering::Relaxed); - - if addr == 0 { - return None; - } - - Some(addr) - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs deleted file mode 100644 index d6ecf677a..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +++ /dev/null @@ -1,138 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Interrupt Controller Driver. - -mod peripheral_ic; - -use crate::{driver, exception, memory, memory::mmu::Physical}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Wrapper struct for a bitmask indicating pending IRQ numbers. -struct PendingIRQs { - bitmask: u64, -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub type LocalIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -pub type PeripheralIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; - -/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -#[derive(Copy, Clone)] -pub enum IRQNumber { - Local(LocalIRQ), - Peripheral(PeripheralIRQ), -} - -/// Representation of the Interrupt Controller. -pub struct InterruptController { - periph: peripheral_ic::PeripheralIC, -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl PendingIRQs { - pub fn new(bitmask: u64) -> Self { - Self { bitmask } - } -} - -impl Iterator for PendingIRQs { - type Item = usize; - - fn next(&mut self) -> Option { - use core::intrinsics::cttz; - - let next = cttz(self.bitmask); - if next == 64 { - return None; - } - - self.bitmask &= !(1 << next); - - Some(next as usize) - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl InterruptController { - const MAX_LOCAL_IRQ_NUMBER: usize = 11; - const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; - const NUM_PERIPHERAL_IRQS: usize = Self::MAX_PERIPHERAL_IRQ_NUMBER + 1; - - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new( - _phys_local_mmio_descriptor: memory::mmu::MMIODescriptor, - phys_periph_mmio_descriptor: memory::mmu::MMIODescriptor, - ) -> Self { - Self { - periph: peripheral_ic::PeripheralIC::new(phys_periph_mmio_descriptor), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ - -impl driver::interface::DeviceDriver for InterruptController { - fn compatible(&self) -> &'static str { - "BCM Interrupt Controller" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - self.periph.init() - } -} - -impl exception::asynchronous::interface::IRQManager for InterruptController { - type IRQNumberType = IRQNumber; - - fn register_handler( - &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, - ) -> Result<(), &'static str> { - match irq { - IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), - IRQNumber::Peripheral(pirq) => self.periph.register_handler(pirq, descriptor), - } - } - - fn enable(&self, irq: Self::IRQNumberType) { - match irq { - IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), - IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), - } - } - - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { - // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. - self.periph.handle_pending_irqs(ic) - } - - fn print_handler(&self) { - self.periph.print_handler(); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs deleted file mode 100644 index 35cf7c1db..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +++ /dev/null @@ -1,191 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Peripheral Interrupt Controller Driver. - -use super::{InterruptController, PendingIRQs, PeripheralIRQ}; -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, - driver, exception, memory, - memory::mmu::Physical, - synchronization, - synchronization::{IRQSafeNullLock, InitStateLock}, -}; -use register::{mmio::*, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -register_structs! { - #[allow(non_snake_case)] - WORegisterBlock { - (0x00 => _reserved1), - (0x10 => ENABLE_1: WriteOnly), - (0x14 => ENABLE_2: WriteOnly), - (0x24 => @END), - } -} - -register_structs! { - #[allow(non_snake_case)] - RORegisterBlock { - (0x00 => _reserved1), - (0x04 => PENDING_1: ReadOnly), - (0x08 => PENDING_2: ReadOnly), - (0x0c => @END), - } -} - -/// Abstraction for the WriteOnly parts of the associated MMIO registers. -type WriteOnlyRegisters = MMIODerefWrapper; - -/// Abstraction for the ReadOnly parts of the associated MMIO registers. -type ReadOnlyRegisters = MMIODerefWrapper; - -type HandlerTable = - [Option; InterruptController::NUM_PERIPHERAL_IRQS]; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Representation of the peripheral interrupt controller. -pub struct PeripheralIC { - phys_mmio_descriptor: memory::mmu::MMIODescriptor, - - /// Access to write registers is guarded with a lock. - wo_registers: IRQSafeNullLock, - - /// Register read access is unguarded. - ro_registers: InitStateLock, - - /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. - handler_table: InitStateLock, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PeripheralIC { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new(phys_mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { - let addr = phys_mmio_descriptor.start_addr().into_usize(); - - Self { - phys_mmio_descriptor, - wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(addr)), - ro_registers: InitStateLock::new(ReadOnlyRegisters::new(addr)), - handler_table: InitStateLock::new([None; InterruptController::NUM_PERIPHERAL_IRQS]), - } - } - - /// Query the list of pending IRQs. - fn pending_irqs(&self) -> PendingIRQs { - self.ro_registers.read(|regs| { - let pending_mask: u64 = - (u64::from(regs.PENDING_2.get()) << 32) | u64::from(regs.PENDING_1.get()); - - PendingIRQs::new(pending_mask) - }) - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::{Mutex, ReadWriteEx}; - -impl driver::interface::DeviceDriver for PeripheralIC { - fn compatible(&self) -> &'static str { - "BCM Peripheral Interrupt Controller" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - let virt_addr = - memory::mmu::kernel_map_mmio(self.compatible(), &self.phys_mmio_descriptor)? - .into_usize(); - - self.wo_registers - .lock(|regs| *regs = WriteOnlyRegisters::new(virt_addr)); - self.ro_registers - .write(|regs| *regs = ReadOnlyRegisters::new(virt_addr)); - - Ok(()) - } -} - -impl exception::asynchronous::interface::IRQManager for PeripheralIC { - type IRQNumberType = PeripheralIRQ; - - fn register_handler( - &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, - ) -> Result<(), &'static str> { - self.handler_table.write(|table| { - let irq_number = irq.get(); - - if table[irq_number].is_some() { - return Err("IRQ handler already registered"); - } - - table[irq_number] = Some(descriptor); - - Ok(()) - }) - } - - fn enable(&self, irq: Self::IRQNumberType) { - self.wo_registers.lock(|regs| { - let enable_reg = if irq.get() <= 31 { - ®s.ENABLE_1 - } else { - ®s.ENABLE_2 - }; - - let enable_bit: u32 = 1 << (irq.get() % 32); - - // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable - // bits are unaffected. So we don't need read and OR'ing here. - enable_reg.set(enable_bit); - }); - } - - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - _ic: &exception::asynchronous::IRQContext<'irq_context>, - ) { - self.handler_table.read(|table| { - for irq_number in self.pending_irqs() { - match table[irq_number] { - None => panic!("No handler registered for IRQ {}", irq_number), - Some(descriptor) => { - // Call the IRQ handler. Panics on failure. - descriptor.handler.handle().expect("Error handling IRQ"); - } - } - } - }) - } - - fn print_handler(&self) { - use crate::info; - - info!(" Peripheral handler:"); - - self.handler_table.read(|table| { - for (i, opt) in table.iter().enumerate() { - if let Some(handler) = opt { - info!(" {: >3}. {}", i, handler.name); - } - } - }); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs deleted file mode 100644 index 374331741..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ /dev/null @@ -1,470 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! PL011 UART driver. - -use crate::{ - bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, memory, - memory::mmu::Physical, synchronization, synchronization::IRQSafeNullLock, -}; -use core::{ - fmt, - sync::atomic::{AtomicUsize, Ordering}, -}; -use register::{mmio::*, register_bitfields, register_structs}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// PL011 UART registers. -// -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf -register_bitfields! { - u32, - - /// Flag Register - FR [ - /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. - TXFE OFFSET(7) NUMBITS(1) [], - - /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. - /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. - TXFF OFFSET(5) NUMBITS(1) [], - - /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. - /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] - ], - - /// Integer Baud rate divisor - IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] - ], - - /// Fractional Baud rate divisor - FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] - ], - - /// Line Control register - LCRH [ - /// Word length. These bits indicate the number of data bits transmitted or received in a - /// frame. - WLEN OFFSET(5) NUMBITS(2) [ - FiveBit = 0b00, - SixBit = 0b01, - SevenBit = 0b10, - EightBit = 0b11 - ], - - /// Enable FIFOs: - /// - /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers - /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). - FEN OFFSET(4) NUMBITS(1) [ - FifosDisabled = 0, - FifosEnabled = 1 - ] - ], - - /// Control Register - CR [ - /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// UART enable - UARTEN OFFSET(0) NUMBITS(1) [ - /// If the UART is disabled in the middle of transmission or reception, it completes the - /// current character before stopping. - Disabled = 0, - Enabled = 1 - ] - ], - - /// Interrupt FIFO Level Select Register - IFLS [ - /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as - /// follows. - RXIFLSEL OFFSET(3) NUMBITS(5) [ - OneEigth = 0b000, - OneQuarter = 0b001, - OneHalf = 0b010, - ThreeQuarters = 0b011, - SevenEights = 0b100 - ] - ], - - /// Interrupt Mask Set Clear Register - IMSC [ - /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR - /// interrupt. On a write of 1, the mask of the interrupt is set. A write of 0 clears the - /// mask. - RTIM OFFSET(6) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ], - - /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. On - /// a write of 1, the mask of the interrupt is set. A write of 0 clears the mask. - RXIM OFFSET(4) NUMBITS(1) [ - Disabled = 0, - Enabled = 1 - ] - ], - - /// Masked Interrupt Status Register - MIS [ - /// Receive timeout masked interrupt status. Returns the masked interrupt state of the - /// UARTRTINTR interrupt. - RTMIS OFFSET(6) NUMBITS(1) [], - - /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR - /// interrupt. - RXMIS OFFSET(4) NUMBITS(1) [] - ], - - /// Interrupt Clear Register - ICR [ - /// Meta field for all pending interrupts - ALL OFFSET(0) NUMBITS(11) [] - ] -} - -register_structs! { - #[allow(non_snake_case)] - pub RegisterBlock { - (0x00 => DR: ReadWrite), - (0x04 => _reserved1), - (0x18 => FR: ReadOnly), - (0x1c => _reserved2), - (0x24 => IBRD: WriteOnly), - (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), - (0x30 => CR: WriteOnly), - (0x34 => IFLS: ReadWrite), - (0x38 => IMSC: ReadWrite), - (0x3C => _reserved3), - (0x40 => MIS: ReadOnly), - (0x44 => ICR: WriteOnly), - (0x48 => @END), - } -} - -/// Abstraction for the associated MMIO registers. -type Registers = MMIODerefWrapper; - -#[derive(PartialEq)] -enum BlockingMode { - Blocking, - NonBlocking, -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct PL011UartInner { - registers: Registers, - chars_written: usize, - chars_read: usize, -} - -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; - -/// Representation of the UART. -pub struct PL011Uart { - phys_mmio_descriptor: memory::mmu::MMIODescriptor, - virt_mmio_start_addr: AtomicUsize, - inner: IRQSafeNullLock, - irq_number: bsp::device_driver::IRQNumber, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl PL011UartInner { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { - Self { - registers: Registers::new(mmio_start_addr), - chars_written: 0, - chars_read: 0, - } - } - - /// Set up baud rate and characteristics. - /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. - /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). - /// - /// # Safety - /// - /// - The user must ensure to provide a correct MMIO start address. - pub unsafe fn init(&mut self, new_mmio_start_addr: Option) -> Result<(), &'static str> { - if let Some(addr) = new_mmio_start_addr { - self.registers = Registers::new(addr); - } - - // Turn it off temporarily. - self.registers.CR.set(0); - - self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); - self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on - self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); // RX FIFO fill level at 1/8 - self.registers - .IMSC - .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); // RX IRQ + RX timeout IRQ - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - - Ok(()) - } - - /// Send a character. - fn write_char(&mut self, c: char) { - // Spin while TX FIFO full is set, waiting for an empty slot. - while self.registers.FR.matches_all(FR::TXFF::SET) { - cpu::nop(); - } - - // Write the character to the buffer. - self.registers.DR.set(c as u32); - - self.chars_written += 1; - } - - /// Retrieve a character. - fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { - // If RX FIFO is empty, - if self.registers.FR.matches_all(FR::RXFE::SET) { - // immediately return in non-blocking mode. - if blocking_mode == BlockingMode::NonBlocking { - return None; - } - - // Otherwise, wait until a char was received. - while self.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - } - - // Read one character. - let mut ret = self.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - self.chars_read += 1; - - Some(ret) - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for PL011UartInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - - Ok(()) - } -} - -impl PL011Uart { - /// Create an instance. - /// - /// # Safety - /// - /// - The user must ensure to provide correct MMIO descriptors. - /// - The user must ensure to provide correct IRQ numbers. - pub const unsafe fn new( - phys_mmio_descriptor: memory::mmu::MMIODescriptor, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { - Self { - phys_mmio_descriptor, - virt_mmio_start_addr: AtomicUsize::new(0), - inner: IRQSafeNullLock::new(PL011UartInner::new( - phys_mmio_descriptor.start_addr().into_usize(), - )), - irq_number, - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -impl driver::interface::DeviceDriver for PL011Uart { - fn compatible(&self) -> &'static str { - "BCM PL011 UART" - } - - unsafe fn init(&self) -> Result<(), &'static str> { - let virt_addr = - memory::mmu::kernel_map_mmio(self.compatible(), &self.phys_mmio_descriptor)?; - - self.inner - .lock(|inner| inner.init(Some(virt_addr.into_usize())))?; - - self.virt_mmio_start_addr - .store(virt_addr.into_usize(), Ordering::Relaxed); - - Ok(()) - } - - fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { - use bsp::exception::asynchronous::irq_manager; - use exception::asynchronous::{interface::IRQManager, IRQDescriptor}; - - let descriptor = IRQDescriptor { - name: "BCM PL011 UART", - handler: self, - }; - - irq_manager().register_handler(self.irq_number, descriptor)?; - irq_manager().enable(self.irq_number); - - Ok(()) - } - - fn virt_mmio_start_addr(&self) -> Option { - let addr = self.virt_mmio_start_addr.load(Ordering::Relaxed); - - if addr == 0 { - return None; - } - - Some(addr) - } -} - -impl console::interface::Write for PL011Uart { - /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to - /// serialize access. - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - fn flush(&self) { - // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); - } -} - -impl console::interface::Read for PL011Uart { - fn read_char(&self) -> char { - self.inner - .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) - } - - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) - } -} - -impl console::interface::Statistics for PL011Uart { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } - - fn chars_read(&self) -> usize { - self.inner.lock(|inner| inner.chars_read) - } -} - -impl exception::asynchronous::interface::IRQHandler for PL011Uart { - fn handle(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| { - let pending = inner.registers.MIS.extract(); - - // Clear all pending IRQs. - inner.registers.ICR.write(ICR::ALL::CLEAR); - - // Check for any kind of RX interrupt. - if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { - // Echo any received characters. - while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { - inner.write_char(c) - } - } - }); - - Ok(()) - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/common.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/common.rs deleted file mode 100644 index cd2c07601..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Common device driver code. - -use core::{marker::PhantomData, ops}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct MMIODerefWrapper { - start_addr: usize, - phantom: PhantomData T>, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl MMIODerefWrapper { - /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { - Self { - start_addr, - phantom: PhantomData, - } - } -} - -impl ops::Deref for MMIODerefWrapper { - type Target = T; - - fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs deleted file mode 100644 index 7ffb72499..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Top-level BSP file for the Raspberry Pi 3 and 4. - -pub mod console; -pub mod cpu; -pub mod driver; -pub mod exception; -pub mod memory; - -use super::device_driver; -use crate::memory::mmu::MMIODescriptor; -use memory::map::mmio; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE)) }; - -static PL011_UART: device_driver::PL011Uart = unsafe { - device_driver::PL011Uart::new( - MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE), - exception::asynchronous::irq_map::PL011_UART, - ) -}; - -#[cfg(feature = "bsp_rpi3")] -static INTERRUPT_CONTROLLER: device_driver::InterruptController = unsafe { - device_driver::InterruptController::new( - MMIODescriptor::new(mmio::LOCAL_IC_START, mmio::LOCAL_IC_SIZE), - MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE), - ) -}; - -#[cfg(feature = "bsp_rpi4")] -static INTERRUPT_CONTROLLER: device_driver::GICv2 = unsafe { - device_driver::GICv2::new( - MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE), - MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE), - ) -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Board identification. -pub fn board_name() -> &'static str { - #[cfg(feature = "bsp_rpi3")] - { - "Raspberry Pi 3" - } - - #[cfg(feature = "bsp_rpi4")] - { - "Raspberry Pi 4" - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs deleted file mode 100644 index c5d0e05a5..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console, cpu}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - use crate::driver::interface::DeviceDriver; - - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START.into_usize()); - let mut panic_uart = - device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.into_usize()); - - // If remapping of the driver's MMIO already happened, take the remapped start address. - // Otherwise, take a chance with the default physical address. - let maybe_gpio_mmio_start_addr = super::GPIO.virt_mmio_start_addr(); - let maybe_uart_mmio_start_addr = super::PL011_UART.virt_mmio_start_addr(); - - panic_gpio - .init(maybe_gpio_mmio_start_addr) - .unwrap_or_else(|_| cpu::wait_forever()); - panic_gpio.map_pl011_uart(); - panic_uart - .init(maybe_uart_mmio_start_addr) - .unwrap_or_else(|_| cpu::wait_forever()); - - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps -/// than on real hardware due to QEMU's abstractions. -/// -/// For the RPi, nothing needs to be done. -pub fn qemu_bring_up_console() {} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/cpu.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 8410a9615..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Processor code. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index 313b957e0..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP driver support. - -use crate::driver; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 3], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [ - &super::GPIO, - &super::PL011_UART, - &super::INTERRUPT_CONTROLLER, - ], -}; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; - -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } - - fn early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[0..=1] - } - - fn non_early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[2..] - } - - fn post_early_print_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception.rs deleted file mode 100644 index 55e821198..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception.rs +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! BSP synchronous and asynchronous exception handling. - -pub mod asynchronous; diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception/asynchronous.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception/asynchronous.rs deleted file mode 100644 index 787d59269..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception/asynchronous.rs +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! BSP asynchronous exception handling. - -use crate::{bsp, exception}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -#[cfg(feature = "bsp_rpi3")] -pub(in crate::bsp) mod irq_map { - use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; - - pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); -} - -#[cfg(feature = "bsp_rpi4")] -pub(in crate::bsp) mod irq_map { - use super::bsp::device_driver::IRQNumber; - - pub const PL011_UART: IRQNumber = IRQNumber::new(153); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the IRQ manager. -pub fn irq_manager() -> &'static impl exception::asynchronous::interface::IRQManager< - IRQNumberType = bsp::device_driver::IRQNumber, -> { - &super::super::INTERRUPT_CONTROLLER -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld deleted file mode 100644 index ae5c28196..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,52 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - __ro_start = .; - .text : - { - *(.text._start) *(.text*) - } - - .exception_vectors : - { - *(.exception_vectors*) - } - - .rodata : - { - *(.rodata*) - } - . = ALIGN(65536); /* Fill up to 64 KiB */ - __ro_end = .; - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - . = ALIGN(65536); - __data_end = .; - - __ro_size = __ro_end - __ro_start; - __data_size = __data_end - __ro_end; - - /DISCARD/ : { *(.comment*) } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs deleted file mode 100644 index 5c05e2080..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs +++ /dev/null @@ -1,194 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management. -//! -//! The physical memory layout after the kernel has been loaded by the Raspberry's firmware, which -//! copies the binary to 0x8_0000: -//! -//! +---------------------------------------------+ -//! | | 0x0 -//! | Unmapped | -//! | | 0x6_FFFF -//! +---------------------------------------------+ -//! | BOOT_CORE_STACK_START | 0x7_0000 -//! | | ^ -//! | ... | | Stack growth direction -//! | | | -//! | BOOT_CORE_STACK_END_INCLUSIVE | 0x7_FFFF -//! +---------------------------------------------+ -//! | RO_START == BOOT_CORE_STACK_END | 0x8_0000 -//! | | -//! | | -//! | .text | -//! | .exception_vectors | -//! | .rodata | -//! | | -//! | RO_END_INCLUSIVE | 0x8_0000 + __ro_size - 1 -//! +---------------------------------------------+ -//! | RO_END == DATA_START | 0x8_0000 + __ro_size -//! | | -//! | .data | -//! | .bss | -//! | | -//! | DATA_END_INCLUSIVE | 0x8_0000 + __ro_size + __data_size - 1 -//! +---------------------------------------------+ - -pub mod mmu; - -use crate::memory::mmu::{Address, Physical, Virtual}; -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; - static __ro_start: UnsafeCell<()>; - static __ro_size: UnsafeCell<()>; - static __data_size: UnsafeCell<()>; -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The board's physical memory map. -#[rustfmt::skip] -pub(super) mod map { - use super::*; - - pub const BOOT_CORE_STACK_SIZE: usize = 0x1_0000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] - pub mod mmio { - use super::*; - - pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); - pub const PERIPHERAL_IC_SIZE: usize = 0x24; - - pub const GPIO_START: Address = Address::new(0x3F20_0000); - pub const GPIO_SIZE: usize = 0xA0; - - pub const PL011_UART_START: Address = Address::new(0x3F20_1000); - pub const PL011_UART_SIZE: usize = 0x48; - - pub const LOCAL_IC_START: Address = Address::new(0x4000_0000); - pub const LOCAL_IC_SIZE: usize = 0x100; - - pub const END: Address = Address::new(0x4001_0000); - } - - /// Physical devices. - #[cfg(feature = "bsp_rpi4")] - pub mod mmio { - use super::*; - - pub const GPIO_START: Address = Address::new(0xFE20_0000); - pub const GPIO_SIZE: usize = 0xA0; - - pub const PL011_UART_START: Address = Address::new(0xFE20_1000); - pub const PL011_UART_SIZE: usize = 0x48; - - pub const GICD_START: Address = Address::new(0xFF84_1000); - pub const GICD_SIZE: usize = 0x824; - - pub const GICC_START: Address = Address::new(0xFF84_2000); - pub const GICC_SIZE: usize = 0x14; - - pub const END: Address = Address::new(0xFF85_0000); - } - - pub const END: Address = mmio::END; -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Start address of the Read-Only (RO) range. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn virt_ro_start() -> Address { - Address::new(unsafe { __ro_start.get() as usize }) -} - -/// Size of the Read-Only (RO) range of the kernel binary. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn ro_size() -> usize { - unsafe { __ro_size.get() as usize } -} - -/// Start address of the data range. -#[inline(always)] -fn virt_data_start() -> Address { - virt_ro_start() + ro_size() -} - -/// Size of the data range. -/// -/// # Safety -/// -/// - Value is provided by the linker script and must be trusted as-is. -#[inline(always)] -fn data_size() -> usize { - unsafe { __data_size.get() as usize } -} - -/// Start address of the boot core's stack. -#[inline(always)] -fn virt_boot_core_stack_start() -> Address { - virt_ro_start() - map::BOOT_CORE_STACK_SIZE -} - -/// Size of the boot core's stack. -#[inline(always)] -fn boot_core_stack_size() -> usize { - map::BOOT_CORE_STACK_SIZE -} - -/// Exclusive end address of the physical address space. -#[inline(always)] -fn phys_addr_space_end() -> Address { - map::END -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn phys_boot_core_stack_end() -> Address { - // The binary is still identity mapped, so we don't need to convert here. - let end = virt_boot_core_stack_start().into_usize() + boot_core_stack_size(); - Address::new(end) -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs b/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs deleted file mode 100644 index 41f55941d..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs +++ /dev/null @@ -1,171 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP Memory Management Unit. - -use crate::{ - common, - memory::{ - mmu as kernel_mmu, - mmu::{ - interface, AccessPermissions, AttributeFields, Granule64KiB, MemAttributes, Page, - PageSliceDescriptor, Physical, Virtual, - }, - }, -}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to -/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. -pub type KernelGranule = Granule64KiB; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- -use interface::TranslationGranule; - -/// Helper function for calculating the number of pages the given parameter spans. -const fn size_to_num_pages(size: usize) -> usize { - assert!(size > 0); - assert!(size % KernelGranule::SIZE == 0); - - size >> KernelGranule::SHIFT -} - -/// The boot core's stack. -fn virt_stack_page_desc() -> PageSliceDescriptor { - let num_pages = size_to_num_pages(super::boot_core_stack_size()); - - PageSliceDescriptor::from_addr(super::virt_boot_core_stack_start(), num_pages) -} - -/// The Read-Only (RO) pages of the kernel binary. -fn virt_ro_page_desc() -> PageSliceDescriptor { - let num_pages = size_to_num_pages(super::ro_size()); - - PageSliceDescriptor::from_addr(super::virt_ro_start(), num_pages) -} - -/// The data pages of the kernel binary. -fn virt_data_page_desc() -> PageSliceDescriptor { - let num_pages = size_to_num_pages(super::data_size()); - - PageSliceDescriptor::from_addr(super::virt_data_start(), num_pages) -} - -// The binary is still identity mapped, so we don't need to convert in the following. - -/// The boot core's stack. -fn phys_stack_page_desc() -> PageSliceDescriptor { - virt_stack_page_desc().into() -} - -/// The Read-Only (RO) pages of the kernel binary. -fn phys_ro_page_desc() -> PageSliceDescriptor { - virt_ro_page_desc().into() -} - -/// The data pages of the kernel binary. -fn phys_data_page_desc() -> PageSliceDescriptor { - virt_data_page_desc().into() -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Pointer to the last page of the physical address space. -pub fn phys_addr_space_end_page() -> *const Page { - common::align_down( - super::phys_addr_space_end().into_usize(), - KernelGranule::SIZE, - ) as *const Page<_> -} - -/// Map the kernel binary. -/// -/// # Safety -/// -/// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking. -pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { - kernel_mmu::kernel_map_pages_at( - "Kernel boot-core stack", - &phys_stack_page_desc(), - &virt_stack_page_desc(), - &AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - )?; - - kernel_mmu::kernel_map_pages_at( - "Kernel code and RO data", - &phys_ro_page_desc(), - &virt_ro_page_desc(), - &AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadOnly, - execute_never: false, - }, - )?; - - kernel_mmu::kernel_map_pages_at( - "Kernel data and bss", - &phys_data_page_desc(), - &virt_data_page_desc(), - &AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - )?; - - Ok(()) -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check alignment of the kernel's virtual memory layout sections. - #[kernel_test] - fn virt_mem_layout_sections_are_64KiB_aligned() { - for i in [virt_stack_page_desc, virt_ro_page_desc, virt_data_page_desc].iter() { - let start: usize = i().start_addr().into_usize(); - let end: usize = i().end_addr().into_usize(); - - assert_eq!(start % KernelGranule::SIZE, 0); - assert_eq!(end % KernelGranule::SIZE, 0); - assert!(end >= start); - } - } - - /// Ensure the kernel's virtual memory layout is free of overlaps. - #[kernel_test] - fn virt_mem_layout_has_no_overlaps() { - let layout = [ - virt_stack_page_desc().into_usize_range_inclusive(), - virt_ro_page_desc().into_usize_range_inclusive(), - virt_data_page_desc().into_usize_range_inclusive(), - ]; - - for (i, first_range) in layout.iter().enumerate() { - for second_range in layout.iter().skip(i + 1) { - assert!(!first_range.contains(second_range.start())); - assert!(!first_range.contains(second_range.end())); - assert!(!second_range.contains(first_range.start())); - assert!(!second_range.contains(first_range.end())); - } - } - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/common.rs b/15_virtual_mem_part2_mmio_remap/src/common.rs deleted file mode 100644 index 58209804b..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/common.rs +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! General purpose code. - -/// Check if a value is aligned to a given size. -#[inline(always)] -pub const fn is_aligned(value: usize, alignment: usize) -> bool { - assert!(alignment.is_power_of_two()); - - (value & (alignment - 1)) == 0 -} - -/// Align down. -#[inline(always)] -pub const fn align_down(value: usize, alignment: usize) -> usize { - assert!(alignment.is_power_of_two()); - - value & !(alignment - 1) -} diff --git a/15_virtual_mem_part2_mmio_remap/src/console.rs b/15_virtual_mem_part2_mmio_remap/src/console.rs deleted file mode 100644 index e6323a20d..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/console.rs +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! System console. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Console interfaces. -pub mod interface { - use core::fmt; - - /// Console write functions. - pub trait Write { - /// Write a single character. - fn write_char(&self, c: char); - - /// Write a Rust format string. - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). - fn flush(&self); - } - - /// Console read functions. - pub trait Read { - /// Read a single character. - fn read_char(&self) -> char { - ' ' - } - - /// Clear RX buffers, if any. - fn clear(&self); - } - - /// Console statistics. - pub trait Statistics { - /// Return the number of characters written. - fn chars_written(&self) -> usize { - 0 - } - - /// Return the number of characters read. - fn chars_read(&self) -> usize { - 0 - } - } - - /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; -} diff --git a/15_virtual_mem_part2_mmio_remap/src/cpu.rs b/15_virtual_mem_part2_mmio_remap/src/cpu.rs deleted file mode 100644 index 9c67c0e7d..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/cpu.rs +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Processor code. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/cpu.rs"] -mod arch_cpu; -pub use arch_cpu::*; - -pub mod smp; diff --git a/15_virtual_mem_part2_mmio_remap/src/cpu/smp.rs b/15_virtual_mem_part2_mmio_remap/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/15_virtual_mem_part2_mmio_remap/src/driver.rs b/15_virtual_mem_part2_mmio_remap/src/driver.rs deleted file mode 100644 index b6875b7f7..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/driver.rs +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Driver support. - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Driver interfaces. -pub mod interface { - /// Device Driver functions. - pub trait DeviceDriver { - /// Return a compatibility string for identifying the driver. - fn compatible(&self) -> &'static str; - - /// Called by the kernel to bring up the device. - /// - /// # Safety - /// - /// - During init, drivers might do stuff with system-wide impact. - unsafe fn init(&self) -> Result<(), &'static str> { - Ok(()) - } - - /// Called by the kernel to register and enable the device's IRQ handlers, if any. - /// - /// Rust's type system will prevent a call to this function unless the calling instance - /// itself has static lifetime. - fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { - Ok(()) - } - - /// After MMIO remapping, returns the new virtual start address. - /// - /// This API assumes a driver has only a single, contiguous MMIO aperture, which will not be - /// the case for more complex devices. This API will likely change in future tutorials. - fn virt_mmio_start_addr(&self) -> Option { - None - } - } - - /// Device driver management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Return only those drivers needed for the BSP's early printing functionality. - /// - /// For example, the default UART. - fn early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Return all drivers minus early-print drivers. - fn non_early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; - - /// Initialization code that runs after the early print driver init. - fn post_early_print_device_driver_init(&self); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/exception.rs b/15_virtual_mem_part2_mmio_remap/src/exception.rs deleted file mode 100644 index 81ea2b26e..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/exception.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronous and asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/exception.rs"] -mod arch_exception; -pub use arch_exception::*; - -pub mod asynchronous; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Kernel privilege levels. -#[allow(missing_docs)] -#[derive(PartialEq)] -pub enum PrivilegeLevel { - User, - Kernel, - Hypervisor, - Unknown, -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Libkernel unit tests must execute in kernel mode. - #[kernel_test] - fn test_runner_executes_in_kernel_mode() { - let (level, _) = current_privilege_level(); - - assert!(level == PrivilegeLevel::Kernel) - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/exception/asynchronous.rs b/15_virtual_mem_part2_mmio_remap/src/exception/asynchronous.rs deleted file mode 100644 index 1a3902a3b..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/exception/asynchronous.rs +++ /dev/null @@ -1,145 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Asynchronous exception handling. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/exception/asynchronous.rs"] -mod arch_exception_async; -pub use arch_exception_async::*; - -use core::{fmt, marker::PhantomData}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Interrupt descriptor. -#[derive(Copy, Clone)] -pub struct IRQDescriptor { - /// Descriptive name. - pub name: &'static str, - - /// Reference to handler trait object. - pub handler: &'static (dyn interface::IRQHandler + Sync), -} - -/// IRQContext token. -/// -/// An instance of this type indicates that the local core is currently executing in IRQ -/// context, aka executing an interrupt vector or subcalls of it. -/// -/// Concept and implementation derived from the `CriticalSection` introduced in -/// https://github.com/rust-embedded/bare-metal -#[derive(Clone, Copy)] -pub struct IRQContext<'irq_context> { - _0: PhantomData<&'irq_context ()>, -} - -/// Asynchronous exception handling interfaces. -pub mod interface { - - /// Implemented by types that handle IRQs. - pub trait IRQHandler { - /// Called when the corresponding interrupt is asserted. - fn handle(&self) -> Result<(), &'static str>; - } - - /// IRQ management functions. - /// - /// The `BSP` is supposed to supply one global instance. Typically implemented by the - /// platform's interrupt controller. - pub trait IRQManager { - /// The IRQ number type depends on the implementation. - type IRQNumberType; - - /// Register a handler. - fn register_handler( - &self, - irq_number: Self::IRQNumberType, - descriptor: super::IRQDescriptor, - ) -> Result<(), &'static str>; - - /// Enable an interrupt in the controller. - fn enable(&self, irq_number: Self::IRQNumberType); - - /// Handle pending interrupts. - /// - /// This function is called directly from the CPU's IRQ exception vector. On AArch64, - /// this means that the respective CPU core has disabled exception handling. - /// This function can therefore not be preempted and runs start to finish. - /// - /// Takes an IRQContext token to ensure it can only be called from IRQ context. - #[allow(clippy::trivially_copy_pass_by_ref)] - fn handle_pending_irqs<'irq_context>( - &'irq_context self, - ic: &super::IRQContext<'irq_context>, - ); - - /// Print list of registered handlers. - fn print_handler(&self); - } -} - -/// A wrapper type for IRQ numbers with integrated range sanity check. -#[derive(Copy, Clone)] -pub struct IRQNumber(usize); - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl<'irq_context> IRQContext<'irq_context> { - /// Creates an IRQContext token. - /// - /// # Safety - /// - /// - This must only be called when the current core is in an interrupt context and will not - /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For - /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. - /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code - /// must not be able to influence the lifetime picked for this type, since that might cause it - /// to be inferred to `'static`. - #[inline(always)] - pub unsafe fn new() -> Self { - IRQContext { _0: PhantomData } - } -} - -impl IRQNumber<{ MAX_INCLUSIVE }> { - /// Creates a new instance if number <= MAX_INCLUSIVE. - pub const fn new(number: usize) -> Self { - assert!(number <= MAX_INCLUSIVE); - - Self { 0: number } - } - - /// Return the wrapped number. - pub fn get(self) -> usize { - self.0 - } -} - -impl fmt::Display for IRQNumber<{ MAX_INCLUSIVE }> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -/// Executes the provided closure while IRQs are masked on the executing core. -/// -/// While the function temporarily changes the HW state of the executing core, it restores it to the -/// previous state before returning, so this is deemed safe. -#[inline(always)] -pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { - let ret: T; - - unsafe { - let saved = local_irq_mask_save(); - ret = f(); - local_irq_restore(saved); - } - - ret -} diff --git a/15_virtual_mem_part2_mmio_remap/src/lib.rs b/15_virtual_mem_part2_mmio_remap/src/lib.rs deleted file mode 100644 index 50789867e..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/lib.rs +++ /dev/null @@ -1,180 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` library. -//! -//! Used by `main.rs` to compose the final kernel binary. -//! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`bsp::exception::asynchronous::irq_manager()`] - Returns a reference to the kernel's [IRQ -//! Handling interface]. -//! - [`memory::mmu::mmu()`] - Returns a reference to the kernel's [MMU interface]. -//! - [`state::state_manager()`] - Returns a reference to the kernel's [state management] instance. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [IRQ Handling interface]: ../libkernel/exception/asynchronous/interface/trait.IRQManager.html -//! [MMU interface]: ../libkernel/memory/mmu/interface/trait.MMU.html -//! [state management]: ../libkernel/state/struct.StateManager.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! -//! # Code organization and architecture -//! -//! The code is divided into different *modules*, each representing a typical **subsystem** of the -//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, -//! `src/memory.rs` contains code that is concerned with all things memory management. -//! -//! ## Visibility of processor architecture code -//! -//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target -//! processor architecture. For each supported processor architecture, there exists a subfolder in -//! `src/_arch`, for example, `src/_arch/aarch64`. -//! -//! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. -//! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. -//! -//! ## BSP code -//! -//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains -//! target board specific definitions and functions. These are things such as the board's memory map -//! or instances of drivers for devices that are featured on the respective board. -//! -//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. -//! -//! ## Kernel interfaces -//! -//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target -//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of -//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` -//! code to play nicely with any of the two without much hassle. -//! -//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, -//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined -//! in the respective subsystem module and help to enforce the idiom of *program to an interface, -//! not an implementation*. For example, there will be a common IRQ handling interface which the two -//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the -//! interface to the rest of the `kernel`. -//! -//! ``` -//! +-------------------+ -//! | Interface (Trait) | -//! | | -//! +--+-------------+--+ -//! ^ ^ -//! | | -//! | | -//! +----------+--+ +--+----------+ -//! | kernel code | | bsp code | -//! | | | arch code | -//! +-------------+ +-------------+ -//! ``` -//! -//! # Summary -//! -//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical -//! locations. Here is an example for the **memory** subsystem: -//! -//! - `src/memory.rs` and `src/memory/**/*` -//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. -//! - Example: A function to zero a chunk of memory. -//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. -//! - Example: An `MMU` interface that defines `MMU` function prototypes. -//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` -//! - `BSP` specific code. -//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). -//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` -//! - Processor architecture specific code. -//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor -//! architecture. -//! -//! From a namespace perspective, **memory** subsystem code lives in: -//! -//! - `crate::memory::*` -//! - `crate::bsp::memory::*` - -#![allow(incomplete_features)] -#![feature(asm)] -#![feature(const_fn)] -#![feature(const_fn_fn_ptr_basics)] -#![feature(const_generics)] -#![feature(const_panic)] -#![feature(core_intrinsics)] -#![feature(format_args_nl)] -#![feature(global_asm)] -#![feature(linkage)] -#![feature(naked_functions)] -#![feature(panic_info_message)] -#![feature(trait_alias)] -#![no_std] -// Testing -#![cfg_attr(test, no_main)] -#![feature(custom_test_frameworks)] -#![reexport_test_harness_main = "test_main"] -#![test_runner(crate::test_runner)] - -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()` (defined in `main.rs`). - -mod panic_wait; -mod runtime_init; -mod synchronization; - -pub mod bsp; -pub mod common; -pub mod console; -pub mod cpu; -pub mod driver; -pub mod exception; -pub mod memory; -pub mod print; -pub mod state; -pub mod time; - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// The default runner for unit tests. -pub fn test_runner(tests: &[&test_types::UnitTest]) { - println!("Running {} tests", tests.len()); - println!("-------------------------------------------------------------------\n"); - for (i, test) in tests.iter().enumerate() { - print!("{:>3}. {:.<58}", i + 1, test.name); - - // Run the actual test. - (test.test_func)(); - - // Failed tests call panic!(). Execution reaches here only if the test has passed. - println!("[ok]") - } -} - -/// The `kernel_init()` for unit tests. Called from `runtime_init()`. -#[cfg(test)] -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - test_main(); - - cpu::qemu_exit_success() -} diff --git a/15_virtual_mem_part2_mmio_remap/src/main.rs b/15_virtual_mem_part2_mmio_remap/src/main.rs deleted file mode 100644 index d693bee68..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/main.rs +++ /dev/null @@ -1,110 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! The `kernel` binary. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -use libkernel::{bsp, cpu, driver, exception, info, memory, state, time, warn}; - -/// Early init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order: -/// - Virtual memory must be activated before the device drivers. -/// - Without it, any atomic operations, e.g. the yet-to-be-introduced spinlocks in the device -/// drivers (which currently employ IRQSafeNullLocks instead of spinlocks), will fail to -/// work on the RPi SoCs. -#[no_mangle] -unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - - exception::handling_init(); - - if let Err(string) = memory::mmu::kernel_map_binary_and_enable_mmu() { - panic!("Enabling MMU failed: {}", string); - } - // Printing will silently fail fail from here on, because the driver's MMIO is not remapped yet. - - // Bring up the drivers needed for printing first. - for i in bsp::driver::driver_manager() - .early_print_device_drivers() - .iter() - { - // Any encountered errors cannot be printed yet, obviously, so just safely park the CPU. - i.init().unwrap_or_else(|_| cpu::wait_forever()); - } - bsp::driver::driver_manager().post_early_print_device_driver_init(); - // Printing available again from here on. - - // Now bring up the remaining drivers. - for i in bsp::driver::driver_manager() - .non_early_print_device_drivers() - .iter() - { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } - } - - // Let device drivers register and enable their handlers with the interrupt controller. - for i in bsp::driver::driver_manager().all_device_drivers() { - if let Err(msg) = i.register_and_enable_irq_handler() { - warn!("Error registering IRQ handler: {}", msg); - } - } - - // Unmask interrupts on the boot CPU core. - exception::asynchronous::local_irq_unmask(); - - // Announce conclusion of the kernel_init() phase. - state::state_manager().transition_to_single_core_main(); - - // Transition from unsafe to safe. - kernel_main() -} - -/// The main function running after the early init. -fn kernel_main() -> ! { - use driver::interface::DriverManager; - use exception::asynchronous::interface::IRQManager; - - info!("Booting on: {}", bsp::board_name()); - - info!("MMU online:"); - memory::mmu::kernel_print_mappings(); - - let (_, privilege_level) = exception::current_privilege_level(); - info!("Current privilege level: {}", privilege_level); - - info!("Exception handling state:"); - exception::asynchronous::print_state(); - - info!( - "Architectural timer resolution: {} ns", - time::time_manager().resolution().as_nanos() - ); - - info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } - - info!("Registered IRQ handlers:"); - bsp::exception::asynchronous::irq_manager().print_handler(); - - info!("Echoing input now"); - cpu::wait_forever(); -} diff --git a/15_virtual_mem_part2_mmio_remap/src/memory.rs b/15_virtual_mem_part2_mmio_remap/src/memory.rs deleted file mode 100644 index 32353d4f6..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/memory.rs +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -pub mod mmu; - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check `zero_volatile()`. - #[kernel_test] - fn zero_volatile_works() { - let mut x: [usize; 3] = [10, 11, 12]; - let x_range = x.as_mut_ptr_range(); - let x_range_inclusive = - RangeInclusive::new(x_range.start, unsafe { x_range.end.offset(-1) }); - - unsafe { zero_volatile(x_range_inclusive) }; - - assert_eq!(x, [0, 0, 0]); - } - - /// Check `bss` section layout. - #[kernel_test] - fn bss_section_is_sane() { - use crate::bsp::memory::bss_range_inclusive; - use core::mem; - - let start = *bss_range_inclusive().start() as usize; - let end = *bss_range_inclusive().end() as usize; - - assert_eq!(start % mem::size_of::(), 0); - assert_eq!(end % mem::size_of::(), 0); - assert!(end >= start); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/memory/mmu.rs b/15_virtual_mem_part2_mmio_remap/src/memory/mmu.rs deleted file mode 100644 index 778fd646f..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/memory/mmu.rs +++ /dev/null @@ -1,250 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Memory Management Unit. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/memory/mmu.rs"] -mod arch_mmu; -pub use arch_mmu::*; - -mod mapping_record; -mod types; - -use crate::{bsp, synchronization, warn}; - -pub use types::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Memory Management interfaces. -pub mod interface { - use super::*; - - /// Describes the characteristics of a translation granule. - #[allow(missing_docs)] - pub trait TranslationGranule { - const SIZE: usize; - const MASK: usize = Self::SIZE - 1; - const SHIFT: usize; - } - - /// Translation table operations. - pub trait TranslationTable { - /// Anything that needs to run before any of the other provided functions can be used. - /// - /// # Safety - /// - /// - Implementor must ensure that this function can run only once or is harmless if invoked - /// multiple times. - unsafe fn init(&mut self); - - /// The translation table's base address to be used for programming the MMU. - fn phys_base_address(&self) -> Address; - - /// Map the given physical pages to the given virtual pages. - /// - /// # Safety - /// - /// - Using wrong attributes can cause multiple issues of different nature in the system. - /// - It is not required that the architectural implementation prevents aliasing. That is, - /// mapping to the same physical memory using multiple virtual addresses, which would - /// break Rust's ownership assumptions. This should be protected against in this module - /// (the kernel's generic MMU code). - unsafe fn map_pages_at( - &mut self, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, - ) -> Result<(), &'static str>; - - /// Obtain a free virtual page slice in the MMIO region. - /// - /// The "MMIO region" is a distinct region of the implementor's choice, which allows - /// differentiating MMIO addresses from others. This can speed up debugging efforts. - /// Ideally, those MMIO addresses are also standing out visually so that a human eye can - /// identify them. For example, by allocating them from near the end of the virtual address - /// space. - fn next_mmio_virt_page_slice( - &mut self, - num_pages: usize, - ) -> Result, &'static str>; - - /// Check if a virtual page splice is in the "MMIO region". - fn is_virt_page_slice_mmio(&self, virt_pages: &PageSliceDescriptor) -> bool; - } - - /// MMU functions. - pub trait MMU { - /// Turns on the MMU. - /// - /// # Safety - /// - /// - Must only be called after the kernel translation tables have been init()'ed. - /// - Changes the HW's global state. - unsafe fn enable( - &self, - phys_kernel_table_base_addr: Address, - ) -> Result<(), &'static str>; - } -} - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- -use interface::{TranslationTable, MMU}; -use synchronization::interface::ReadWriteEx; - -/// Map pages in the kernel's translation tables. -/// -/// No input checks done, input is passed through to the architectural implementation. -/// -/// # Safety -/// -/// - See `map_pages_at()`. -/// - Does not prevent aliasing. -unsafe fn kernel_map_pages_at_unchecked( - name: &'static str, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, -) -> Result<(), &'static str> { - arch_mmu::kernel_translation_tables() - .write(|tables| tables.map_pages_at(phys_pages, virt_pages, attr))?; - - if let Err(x) = mapping_record::kernel_add(name, phys_pages, virt_pages, attr) { - warn!("{}", x); - } - - Ok(()) -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use interface::TranslationGranule; - -/// Raw mapping of virtual to physical pages in the kernel translation tables. -/// -/// Prevents mapping into the MMIO range of the tables. -/// -/// # Safety -/// -/// - See `kernel_map_pages_at_unchecked()`. -/// - Does not prevent aliasing. Currently, we have to trust the callers. -pub unsafe fn kernel_map_pages_at( - name: &'static str, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, -) -> Result<(), &'static str> { - let is_mmio = arch_mmu::kernel_translation_tables() - .read(|tables| tables.is_virt_page_slice_mmio(virt_pages)); - if is_mmio { - return Err("Attempt to manually map into MMIO region"); - } - - kernel_map_pages_at_unchecked(name, phys_pages, virt_pages, attr)?; - - Ok(()) -} - -/// MMIO remapping in the kernel translation tables. -/// -/// Typically used by device drivers. -/// -/// # Safety -/// -/// - Same as `kernel_map_pages_at_unchecked()`, minus the aliasing part. -pub unsafe fn kernel_map_mmio( - name: &'static str, - phys_mmio_descriptor: &MMIODescriptor, -) -> Result, &'static str> { - let phys_pages: PageSliceDescriptor = phys_mmio_descriptor.clone().into(); - let offset_into_start_page = - phys_mmio_descriptor.start_addr().into_usize() & bsp::memory::mmu::KernelGranule::MASK; - - // Check if an identical page slice has been mapped for another driver. If so, reuse it. - let virt_addr = if let Some(addr) = - mapping_record::kernel_find_and_insert_mmio_duplicate(phys_mmio_descriptor, name) - { - addr - // Otherwise, allocate a new virtual page slice and map it. - } else { - let virt_pages: PageSliceDescriptor = arch_mmu::kernel_translation_tables() - .write(|tables| tables.next_mmio_virt_page_slice(phys_pages.num_pages()))?; - - kernel_map_pages_at_unchecked( - name, - &phys_pages, - &virt_pages, - &AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - )?; - - virt_pages.start_addr() - }; - - Ok(virt_addr + offset_into_start_page) -} - -/// Map the kernel's binary and enable the MMU. -/// -/// # Safety -/// -/// - Crucial function during kernel init. Changes the the complete memory view of the processor. -pub unsafe fn kernel_map_binary_and_enable_mmu() -> Result<(), &'static str> { - let phys_base_addr = arch_mmu::kernel_translation_tables().write(|tables| { - tables.init(); - tables.phys_base_address() - }); - - bsp::memory::mmu::kernel_map_binary()?; - arch_mmu::mmu().enable(phys_base_addr) -} - -/// Human-readable print of all recorded kernel mappings. -pub fn kernel_print_mappings() { - mapping_record::kernel_print() -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Sanity checks for the kernel TranslationTable implementation. - #[kernel_test] - fn translationtable_implementation_sanity() { - // Need to take care that `tables` fits into the stack. - let mut tables = MinSizeArchTranslationTable::new(); - - unsafe { tables.init() }; - - let x = tables.next_mmio_virt_page_slice(0); - assert!(x.is_err()); - - let x = tables.next_mmio_virt_page_slice(1_0000_0000); - assert!(x.is_err()); - - let x = tables.next_mmio_virt_page_slice(2).unwrap(); - assert_eq!(x.size(), bsp::memory::mmu::KernelGranule::SIZE * 2); - - assert_eq!(tables.is_virt_page_slice_mmio(&x), true); - - assert_eq!( - tables.is_virt_page_slice_mmio(&PageSliceDescriptor::from_addr(Address::new(0), 1)), - false - ); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs b/15_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs deleted file mode 100644 index f46e629ed..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs +++ /dev/null @@ -1,221 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! A record of mapped pages. - -use super::{ - AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, - PageSliceDescriptor, Physical, Virtual, -}; -use crate::{info, synchronization, synchronization::InitStateLock, warn}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Type describing a virtual memory mapping. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -struct MappingRecordEntry { - pub users: [Option<&'static str>; 5], - pub phys_pages: PageSliceDescriptor, - pub virt_start_addr: Address, - pub attribute_fields: AttributeFields, -} - -struct MappingRecord { - inner: [Option; 12], -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static KERNEL_MAPPING_RECORD: InitStateLock = - InitStateLock::new(MappingRecord::new()); - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl MappingRecordEntry { - pub fn new( - name: &'static str, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, - ) -> Self { - Self { - users: [Some(name), None, None, None, None], - phys_pages: *phys_pages, - virt_start_addr: virt_pages.start_addr(), - attribute_fields: *attr, - } - } - - fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { - if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { - return Ok(x); - }; - - Err("Storage for user info exhausted") - } - - pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { - let x = self.find_next_free_user()?; - *x = Some(user); - Ok(()) - } -} - -impl MappingRecord { - pub const fn new() -> Self { - Self { inner: [None; 12] } - } - - fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { - if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { - return Ok(x); - } - - Err("Storage for mapping info exhausted") - } - - fn find_duplicate( - &mut self, - phys_pages: &PageSliceDescriptor, - ) -> Option<&mut MappingRecordEntry> { - self.inner - .iter_mut() - .filter(|x| x.is_some()) - .map(|x| x.as_mut().unwrap()) - .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) - .find(|x| x.phys_pages == *phys_pages) - } - - pub fn add( - &mut self, - name: &'static str, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, - ) -> Result<(), &'static str> { - let x = self.find_next_free()?; - - *x = Some(MappingRecordEntry::new(name, phys_pages, virt_pages, attr)); - Ok(()) - } - - pub fn print(&self) { - const KIB_RSHIFT: u32 = 10; // log2(1024). - const MIB_RSHIFT: u32 = 20; // log2(1024 * 1024). - - info!(" -----------------------------------------------------------------------------------------------------------------"); - info!( - " {:^24} {:^24} {:^7} {:^9} {:^35}", - "Virtual", "Physical", "Size", "Attr", "Entity" - ); - info!(" -----------------------------------------------------------------------------------------------------------------"); - - for i in self - .inner - .iter() - .filter(|x| x.is_some()) - .map(|x| x.unwrap()) - { - let virt_start = i.virt_start_addr.into_usize(); - let virt_end_inclusive = virt_start + i.phys_pages.size() - 1; - let phys_start = i.phys_pages.start_addr().into_usize(); - let phys_end_inclusive = i.phys_pages.end_addr_inclusive().into_usize(); - let size = i.phys_pages.size(); - - let (size, unit) = if (size >> MIB_RSHIFT) > 0 { - (size >> MIB_RSHIFT, "MiB") - } else if (size >> KIB_RSHIFT) > 0 { - (size >> KIB_RSHIFT, "KiB") - } else { - (size, "Byte") - }; - - let attr = match i.attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => "C", - MemAttributes::Device => "Dev", - }; - - let acc_p = match i.attribute_fields.acc_perms { - AccessPermissions::ReadOnly => "RO", - AccessPermissions::ReadWrite => "RW", - }; - - let xn = if i.attribute_fields.execute_never { - "XN" - } else { - "X" - }; - - info!( - " {:#011X}..{:#011X} --> {:#011X}..{:#011X} | \ - {: >3} {} | {: <3} {} {: <2} | {}", - virt_start, - virt_end_inclusive, - phys_start, - phys_end_inclusive, - size, - unit, - attr, - acc_p, - xn, - i.users[0].unwrap() - ); - - for k in i.users[1..].iter() { - if let Some(additional_user) = *k { - info!( - " | {}", - additional_user - ); - } - } - } - - info!(" -----------------------------------------------------------------------------------------------------------------"); - } -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- -use synchronization::interface::ReadWriteEx; - -/// Add an entry to the mapping info record. -pub fn kernel_add( - name: &'static str, - phys_pages: &PageSliceDescriptor, - virt_pages: &PageSliceDescriptor, - attr: &AttributeFields, -) -> Result<(), &'static str> { - KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, phys_pages, virt_pages, attr)) -} - -pub fn kernel_find_and_insert_mmio_duplicate( - phys_mmio_descriptor: &MMIODescriptor, - new_user: &'static str, -) -> Option> { - let phys_pages: PageSliceDescriptor = phys_mmio_descriptor.clone().into(); - - KERNEL_MAPPING_RECORD.write(|mr| { - let dup = mr.find_duplicate(&phys_pages)?; - - if let Err(x) = dup.add_user(new_user) { - warn!("{}", x); - } - - Some(dup.virt_start_addr) - }) -} - -/// Human-readable print of all recorded kernel mappings. -pub fn kernel_print() { - KERNEL_MAPPING_RECORD.read(|mr| mr.print()); -} diff --git a/15_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs b/15_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs deleted file mode 100644 index d0098f6f2..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs +++ /dev/null @@ -1,283 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Memory Management Unit Types. - -use crate::{bsp, common}; -use core::{convert::From, marker::PhantomData, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- -use super::interface::TranslationGranule; - -/// Metadata trait for marking the type of an address. -pub trait AddressType: Copy + Clone + PartialOrd + PartialEq {} - -/// Zero-sized type to mark a physical address. -#[derive(Copy, Clone, PartialOrd, PartialEq)] -pub enum Physical {} - -/// Zero-sized type to mark a virtual address. -#[derive(Copy, Clone, PartialOrd, PartialEq)] -pub enum Virtual {} - -/// Generic address type. -#[derive(Copy, Clone, PartialOrd, PartialEq)] -pub struct Address { - value: usize, - _address_type: PhantomData, -} - -/// Generic page type. -#[repr(C)] -pub struct Page { - inner: [u8; bsp::memory::mmu::KernelGranule::SIZE], - _address_type: PhantomData, -} - -/// Type describing a slice of pages. -#[derive(Copy, Clone, PartialOrd, PartialEq)] -pub struct PageSliceDescriptor { - start: Address, - num_pages: usize, -} - -/// Architecture agnostic memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone, PartialOrd, PartialEq)] -pub enum MemAttributes { - CacheableDRAM, - Device, -} - -/// Architecture agnostic access permissions. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum AccessPermissions { - ReadOnly, - ReadWrite, -} - -/// Collection of memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub struct AttributeFields { - pub mem_attributes: MemAttributes, - pub acc_perms: AccessPermissions, - pub execute_never: bool, -} - -/// An MMIO descriptor for use in device drivers. -#[derive(Copy, Clone)] -pub struct MMIODescriptor { - start_addr: Address, - size: usize, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -impl AddressType for Physical {} -impl AddressType for Virtual {} - -//------------------------------------------------------------------------------ -// Address -//------------------------------------------------------------------------------ - -impl Address { - /// Create an instance. - pub const fn new(value: usize) -> Self { - Self { - value, - _address_type: PhantomData, - } - } - - /// Align down. - pub const fn align_down(self, alignment: usize) -> Self { - let aligned = common::align_down(self.value, alignment); - - Self { - value: aligned, - _address_type: PhantomData, - } - } - - /// Converts `Address` into an usize. - pub const fn into_usize(self) -> usize { - self.value - } -} - -impl core::ops::Add for Address { - type Output = Self; - - fn add(self, other: usize) -> Self { - Self { - value: self.value + other, - _address_type: PhantomData, - } - } -} - -impl core::ops::Sub for Address { - type Output = Self; - - fn sub(self, other: usize) -> Self { - Self { - value: self.value - other, - _address_type: PhantomData, - } - } -} - -//------------------------------------------------------------------------------ -// Page -//------------------------------------------------------------------------------ - -impl Page { - /// Get a pointer to the instance. - pub const fn as_ptr(&self) -> *const Page { - self as *const _ - } -} - -//------------------------------------------------------------------------------ -// PageSliceDescriptor -//------------------------------------------------------------------------------ - -impl PageSliceDescriptor { - /// Create an instance. - pub const fn from_addr(start: Address, num_pages: usize) -> Self { - assert!(common::is_aligned( - start.into_usize(), - bsp::memory::mmu::KernelGranule::SIZE - )); - assert!(num_pages > 0); - - Self { start, num_pages } - } - - /// Return a pointer to the first page of the described slice. - const fn first_page_ptr(&self) -> *const Page { - self.start.into_usize() as *const _ - } - - /// Return the number of Pages the slice describes. - pub const fn num_pages(&self) -> usize { - self.num_pages - } - - /// Return the memory size this descriptor spans. - pub const fn size(&self) -> usize { - self.num_pages * bsp::memory::mmu::KernelGranule::SIZE - } - - /// Return the start address. - pub const fn start_addr(&self) -> Address { - self.start - } - - /// Return the exclusive end address. - pub fn end_addr(&self) -> Address { - self.start + self.size() - } - - /// Return the inclusive end address. - pub fn end_addr_inclusive(&self) -> Address { - self.start + (self.size() - 1) - } - - /// Return a non-mutable slice of Pages. - /// - /// # Safety - /// - /// - Same as applies for `core::slice::from_raw_parts`. - pub unsafe fn as_slice(&self) -> &[Page] { - core::slice::from_raw_parts(self.first_page_ptr(), self.num_pages) - } - - /// Return the inclusive address range of the slice. - pub fn into_usize_range_inclusive(self) -> RangeInclusive { - RangeInclusive::new( - self.start_addr().into_usize(), - self.end_addr_inclusive().into_usize(), - ) - } -} - -impl From> for PageSliceDescriptor { - fn from(desc: PageSliceDescriptor) -> Self { - Self { - start: Address::new(desc.start.into_usize()), - num_pages: desc.num_pages, - } - } -} - -impl From> for PageSliceDescriptor { - fn from(desc: MMIODescriptor) -> Self { - let start_page_addr = desc - .start_addr - .align_down(bsp::memory::mmu::KernelGranule::SIZE); - - let len = ((desc.end_addr_inclusive().into_usize() - start_page_addr.into_usize()) - >> bsp::memory::mmu::KernelGranule::SHIFT) - + 1; - - Self { - start: start_page_addr, - num_pages: len, - } - } -} - -//------------------------------------------------------------------------------ -// MMIODescriptor -//------------------------------------------------------------------------------ - -impl MMIODescriptor { - /// Create an instance. - pub const fn new(start_addr: Address, size: usize) -> Self { - assert!(size > 0); - - Self { start_addr, size } - } - - /// Return the start address. - pub const fn start_addr(&self) -> Address { - self.start_addr - } - - /// Return the inclusive end address. - pub fn end_addr_inclusive(&self) -> Address { - self.start_addr + (self.size - 1) - } - - /// Return the size. - pub const fn size(&self) -> usize { - self.size - } -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use test_macros::kernel_test; - - /// Check if the size of `struct Page` is as expected. - #[kernel_test] - fn size_of_page_equals_granule_size() { - assert_eq!( - core::mem::size_of::>(), - bsp::memory::mmu::KernelGranule::SIZE - ); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/panic_wait.rs b/15_virtual_mem_part2_mmio_remap/src/panic_wait.rs deleted file mode 100644 index 52a89d172..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/panic_wait.rs +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! A panic handler that infinitely waits. - -use crate::{bsp, cpu, exception}; -use core::{fmt, panic::PanicInfo}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// The point of exit for the "standard" (non-testing) `libkernel`. -/// -/// This code will be used by the release kernel binary and the `integration tests`. It is linked -/// weakly, so that the integration tests can overload it to exit `QEMU` instead of spinning -/// forever. -/// -/// This is one possible approach to solve the problem that `cargo` can not know who the consumer of -/// the library will be: -/// - The release kernel binary that should safely park the paniced core, -/// - or an `integration test` that is executed in QEMU, which should just exit QEMU. -#[cfg(not(test))] -#[linkage = "weak"] -#[no_mangle] -fn _panic_exit() -> ! { - cpu::wait_forever() -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - unsafe { exception::asynchronous::local_irq_mask() }; - - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } - - _panic_exit() -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -/// The point of exit when the library is compiled for testing. -#[cfg(test)] -#[no_mangle] -fn _panic_exit() -> ! { - cpu::qemu_exit_failure() -} diff --git a/15_virtual_mem_part2_mmio_remap/src/print.rs b/15_virtual_mem_part2_mmio_remap/src/print.rs deleted file mode 100644 index 8b6f3f988..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/print.rs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Printing facilities. - -use crate::{bsp, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -#[doc(hidden)] -pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); -} - -/// Prints without a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! print { - ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); -} - -/// Prints with a newline. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! println { - () => ($crate::print!("\n")); - ($($arg:tt)*) => ({ - $crate::print::_print(format_args_nl!($($arg)*)); - }) -} - -/// Prints an info, with a newline. -#[macro_export] -macro_rules! info { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} - -/// Prints a warning, with a newline. -#[macro_export] -macro_rules! warn { - ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 - )); - }); - ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); - - $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), - timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, - $($arg)* - )); - }) -} diff --git a/15_virtual_mem_part2_mmio_remap/src/runtime_init.rs b/15_virtual_mem_part2_mmio_remap/src/runtime_init.rs deleted file mode 100644 index 1306578dd..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/runtime_init.rs +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - extern "Rust" { - fn kernel_init() -> !; - } - - zero_bss(); - kernel_init() -} diff --git a/15_virtual_mem_part2_mmio_remap/src/state.rs b/15_virtual_mem_part2_mmio_remap/src/state.rs deleted file mode 100644 index af1d93482..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/state.rs +++ /dev/null @@ -1,92 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! State information about the kernel itself. - -use core::sync::atomic::{AtomicU8, Ordering}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// Different stages in the kernel execution. -#[derive(Copy, Clone, Eq, PartialEq)] -enum State { - /// The kernel starts booting in this state. - Init, - - /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of - /// `kernel_init()`, after all init calls are done). - SingleCoreMain, - - /// The kernel transitions to this state when it boots the secondary cores, aka switches - /// exectution mode to symmetric multiprocessing (SMP). - MultiCoreMain, -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Maintains the kernel state and state transitions. -pub struct StateManager(AtomicU8); - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static STATE_MANAGER: StateManager = StateManager::new(); - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the global StateManager. -pub fn state_manager() -> &'static StateManager { - &STATE_MANAGER -} - -impl StateManager { - const INIT: u8 = 0; - const SINGLE_CORE_MAIN: u8 = 1; - const MULTI_CORE_MAIN: u8 = 2; - - /// Create a new instance. - pub const fn new() -> Self { - Self(AtomicU8::new(Self::INIT)) - } - - /// Return the current state. - fn state(&self) -> State { - let state = self.0.load(Ordering::Acquire); - - match state { - Self::INIT => State::Init, - Self::SINGLE_CORE_MAIN => State::SingleCoreMain, - Self::MULTI_CORE_MAIN => State::MultiCoreMain, - _ => panic!("Invalid KERNEL_STATE"), - } - } - - /// Return if the kernel is still in an init state. - pub fn is_init(&self) -> bool { - self.state() == State::Init - } - - /// Transition from Init to SingleCoreMain. - pub fn transition_to_single_core_main(&self) { - if self - .0 - .compare_exchange( - Self::INIT, - Self::SINGLE_CORE_MAIN, - Ordering::Acquire, - Ordering::Relaxed, - ) - .is_err() - { - panic!("transition_to_single_core_main() called while state != Init"); - } - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/synchronization.rs b/15_virtual_mem_part2_mmio_remap/src/synchronization.rs deleted file mode 100644 index 039df47a4..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/synchronization.rs +++ /dev/null @@ -1,140 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Synchronization primitives. -//! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html - -use core::cell::UnsafeCell; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Synchronization interfaces. -pub mod interface { - - /// Any object implementing this trait guarantees exclusive access to the data wrapped within - /// the Mutex for the duration of the provided closure. - pub trait Mutex { - /// The type of the data that is wrapped by this mutex. - type Data; - - /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - } - - /// A reader-writer exclusion type. - /// - /// The implementing object allows either a number of readers or at most one writer at any point - /// in time. - pub trait ReadWriteEx { - /// The type of encapsulated data. - type Data; - - /// Grants temporary mutable access to the encapsulated data. - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; - - /// Grants temporary immutable access to the encapsulated data. - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R; - } -} - -/// A pseudo-lock for teaching purposes. -/// -/// In contrast to a real Mutex implementation, does not protect against concurrent access from -/// other cores to the contained data. This part is preserved for later lessons. -/// -/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing on a single core. -pub struct IRQSafeNullLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. -/// -/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. -pub struct InitStateLock -where - T: ?Sized, -{ - data: UnsafeCell, -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} -unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} - -impl IRQSafeNullLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -unsafe impl Send for InitStateLock where T: ?Sized + Send {} -unsafe impl Sync for InitStateLock where T: ?Sized + Send {} - -impl InitStateLock { - /// Create an instance. - pub const fn new(data: T) -> Self { - Self { - data: UnsafeCell::new(data), - } - } -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use crate::{exception, state}; - -impl interface::Mutex for IRQSafeNullLock { - type Data = T; - - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - // In a real lock, there would be code encapsulating this line that ensures that this - // mutable reference will ever only be given out once at a time. - let data = unsafe { &mut *self.data.get() }; - - // Execute the closure while IRQs are masked. - exception::asynchronous::exec_with_irq_masked(|| f(data)) - } -} - -impl interface::ReadWriteEx for InitStateLock { - type Data = T; - - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { - assert!( - state::state_manager().is_init(), - "InitStateLock::write called after kernel init phase" - ); - assert!( - !exception::asynchronous::is_local_irq_masked(), - "InitStateLock::write called with IRQs unmasked" - ); - - let data = unsafe { &mut *self.data.get() }; - - f(data) - } - - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { - let data = unsafe { &*self.data.get() }; - - f(data) - } -} diff --git a/15_virtual_mem_part2_mmio_remap/src/time.rs b/15_virtual_mem_part2_mmio_remap/src/time.rs deleted file mode 100644 index cd3ceec33..000000000 --- a/15_virtual_mem_part2_mmio_remap/src/time.rs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; -pub use arch_time::*; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); - } -} diff --git a/15_virtual_mem_part2_mmio_remap/test-macros/Cargo.toml b/15_virtual_mem_part2_mmio_remap/test-macros/Cargo.toml deleted file mode 100644 index a570f72b4..000000000 --- a/15_virtual_mem_part2_mmio_remap/test-macros/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "test-macros" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1.x" -quote = "1.x" -syn = { version = "1.x", features = ["full"] } -test-types = { path = "../test-types" } diff --git a/15_virtual_mem_part2_mmio_remap/test-macros/src/lib.rs b/15_virtual_mem_part2_mmio_remap/test-macros/src/lib.rs deleted file mode 100644 index 092c4806e..000000000 --- a/15_virtual_mem_part2_mmio_remap/test-macros/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -use proc_macro::TokenStream; -use proc_macro2::Span; -use quote::quote; -use syn::{parse_macro_input, Ident, ItemFn}; - -#[proc_macro_attribute] -pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { - let f = parse_macro_input!(input as ItemFn); - - let test_name = &format!("{}", f.sig.ident.to_string()); - let test_ident = Ident::new( - &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), - Span::call_site(), - ); - let test_code_block = f.block; - - quote!( - #[test_case] - const #test_ident: test_types::UnitTest = test_types::UnitTest { - name: #test_name, - test_func: || #test_code_block, - }; - ) - .into() -} diff --git a/15_virtual_mem_part2_mmio_remap/test-types/Cargo.toml b/15_virtual_mem_part2_mmio_remap/test-types/Cargo.toml deleted file mode 100644 index a0be2c57c..000000000 --- a/15_virtual_mem_part2_mmio_remap/test-types/Cargo.toml +++ /dev/null @@ -1,5 +0,0 @@ -[package] -name = "test-types" -version = "0.1.0" -authors = ["Andre Richter "] -edition = "2018" diff --git a/15_virtual_mem_part2_mmio_remap/test-types/src/lib.rs b/15_virtual_mem_part2_mmio_remap/test-types/src/lib.rs deleted file mode 100644 index 371bb5574..000000000 --- a/15_virtual_mem_part2_mmio_remap/test-types/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Types for the `custom_test_frameworks` implementation. - -#![no_std] - -/// Unit test container. -pub struct UnitTest { - /// Name of the test. - pub name: &'static str, - - /// Function pointer to the test. - pub test_func: fn(), -} diff --git a/15_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rb b/15_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rb deleted file mode 100644 index a6b549b2a..000000000 --- a/15_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rb +++ /dev/null @@ -1,50 +0,0 @@ -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2019-2020 Andre Richter - -require 'expect' - -TIMEOUT_SECS = 3 - -# Verify sending and receiving works as expected. -class TxRxHandshake - def name - 'Transmit and Receive handshake' - end - - def run(qemu_out, qemu_in) - qemu_in.write_nonblock('ABC') - raise('TX/RX test failed') if qemu_out.expect('OK1234', TIMEOUT_SECS).nil? - end -end - -# Check for correct TX statistics implementation. Depends on test 1 being run first. -class TxStatistics - def name - 'Transmit statistics' - end - - def run(qemu_out, _qemu_in) - raise('chars_written reported wrong') if qemu_out.expect('6', TIMEOUT_SECS).nil? - end -end - -# Check for correct RX statistics implementation. Depends on test 1 being run first. -class RxStatistics - def name - 'Receive statistics' - end - - def run(qemu_out, _qemu_in) - raise('chars_read reported wrong') if qemu_out.expect('3', TIMEOUT_SECS).nil? - end -end - -##-------------------------------------------------------------------------------------------------- -## Test registration -##-------------------------------------------------------------------------------------------------- -def subtest_collection - [TxRxHandshake.new, TxStatistics.new, RxStatistics.new] -end diff --git a/15_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rs b/15_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rs deleted file mode 100644 index 5aa38f098..000000000 --- a/15_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rs +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Console sanity tests - RX, TX and statistics. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -mod panic_exit_failure; - -use libkernel::{bsp, console, print}; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - use bsp::console::{console, qemu_bring_up_console}; - use console::interface::*; - - qemu_bring_up_console(); - - // Handshake - assert_eq!(console().read_char(), 'A'); - assert_eq!(console().read_char(), 'B'); - assert_eq!(console().read_char(), 'C'); - print!("OK1234"); - - // 6 - print!("{}", console().chars_written()); - - // 3 - print!("{}", console().chars_read()); - - // The QEMU process running this test will be closed by the I/O test harness. - loop {} -} diff --git a/15_virtual_mem_part2_mmio_remap/tests/01_timer_sanity.rs b/15_virtual_mem_part2_mmio_remap/tests/01_timer_sanity.rs deleted file mode 100644 index e0b3c1622..000000000 --- a/15_virtual_mem_part2_mmio_remap/tests/01_timer_sanity.rs +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Timer sanity tests. - -#![feature(custom_test_frameworks)] -#![no_main] -#![no_std] -#![reexport_test_harness_main = "test_main"] -#![test_runner(libkernel::test_runner)] - -mod panic_exit_failure; - -use core::time::Duration; -use libkernel::{bsp, cpu, time, time::interface::TimeManager}; -use test_macros::kernel_test; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. - - test_main(); - - cpu::qemu_exit_success() -} - -/// Simple check that the timer is running. -#[kernel_test] -fn timer_is_counting() { - assert!(time::time_manager().uptime().as_nanos() > 0) -} - -/// Timer resolution must be sufficient. -#[kernel_test] -fn timer_resolution_is_sufficient() { - assert!(time::time_manager().resolution().as_nanos() < 100) -} - -/// Sanity check spin_for() implementation. -#[kernel_test] -fn spin_accuracy_check_1_second() { - let t1 = time::time_manager().uptime(); - time::time_manager().spin_for(Duration::from_secs(1)); - let t2 = time::time_manager().uptime(); - - assert_eq!((t2 - t1).as_secs(), 1) -} diff --git a/15_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs b/15_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs deleted file mode 100644 index 0e219a8fb..000000000 --- a/15_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -//! Page faults must result in synchronous exceptions. - -#![feature(format_args_nl)] -#![no_main] -#![no_std] - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -/// -/// Reaching this code is a success, because it is called from the synchronous exception handler, -/// which is what this test wants to achieve. -/// -/// It also means that this integration test can not use any other code that calls panic!() directly -/// or indirectly. -mod panic_exit_success; - -use libkernel::{bsp, cpu, exception, memory, println}; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - use libkernel::driver::interface::DriverManager; - - bsp::console::qemu_bring_up_console(); - - println!("Testing synchronous exception handling by causing a page fault"); - println!("-------------------------------------------------------------------\n"); - - exception::handling_init(); - - if let Err(string) = memory::mmu::kernel_map_binary_and_enable_mmu() { - println!("Enabling MMU failed: {}", string); - cpu::qemu_exit_failure() - } - // Printing will silently fail fail from here on, because the driver's MMIO is not remapped yet. - - // Bring up the drivers needed for printing first. - for i in bsp::driver::driver_manager() - .early_print_device_drivers() - .iter() - { - // Any encountered errors cannot be printed yet, obviously, so just safely park the CPU. - i.init().unwrap_or_else(|_| cpu::qemu_exit_failure()); - } - bsp::driver::driver_manager().post_early_print_device_driver_init(); - // Printing available again from here on. - - println!("Writing beyond mapped area to address 9 GiB..."); - let big_addr: u64 = 9 * 1024 * 1024 * 1024; - core::ptr::read_volatile(big_addr as *mut u64); - - // If execution reaches here, the memory access above did not cause a page fault exception. - cpu::qemu_exit_failure() -} diff --git a/15_virtual_mem_part2_mmio_remap/tests/03_exception_irq_sanity.rs b/15_virtual_mem_part2_mmio_remap/tests/03_exception_irq_sanity.rs deleted file mode 100644 index 6e2ae8f7c..000000000 --- a/15_virtual_mem_part2_mmio_remap/tests/03_exception_irq_sanity.rs +++ /dev/null @@ -1,68 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020 Andre Richter - -//! IRQ handling sanity tests. - -#![feature(custom_test_frameworks)] -#![no_main] -#![no_std] -#![reexport_test_harness_main = "test_main"] -#![test_runner(libkernel::test_runner)] - -mod panic_exit_failure; - -use libkernel::{bsp, cpu, exception}; -use test_macros::kernel_test; - -#[no_mangle] -unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); - - exception::handling_init(); - exception::asynchronous::local_irq_unmask(); - - test_main(); - - cpu::qemu_exit_success() -} - -/// Check that IRQ masking works. -#[kernel_test] -fn local_irq_mask_works() { - // Precondition: IRQs are unmasked. - assert!(exception::asynchronous::is_local_irq_masked()); - - unsafe { exception::asynchronous::local_irq_mask() }; - assert!(!exception::asynchronous::is_local_irq_masked()); - - // Restore earlier state. - unsafe { exception::asynchronous::local_irq_unmask() }; -} - -/// Check that IRQ unmasking works. -#[kernel_test] -fn local_irq_unmask_works() { - // Precondition: IRQs are masked. - unsafe { exception::asynchronous::local_irq_mask() }; - assert!(!exception::asynchronous::is_local_irq_masked()); - - unsafe { exception::asynchronous::local_irq_unmask() }; - assert!(exception::asynchronous::is_local_irq_masked()); -} - -/// Check that IRQ mask save is saving "something". -#[kernel_test] -fn local_irq_mask_save_works() { - // Precondition: IRQs are unmasked. - assert!(exception::asynchronous::is_local_irq_masked()); - - let first = unsafe { exception::asynchronous::local_irq_mask_save() }; - assert!(!exception::asynchronous::is_local_irq_masked()); - - let second = unsafe { exception::asynchronous::local_irq_mask_save() }; - assert_ne!(first, second); - - unsafe { exception::asynchronous::local_irq_restore(first) }; - assert!(exception::asynchronous::is_local_irq_masked()); -} diff --git a/15_virtual_mem_part2_mmio_remap/tests/panic_exit_failure/mod.rs b/15_virtual_mem_part2_mmio_remap/tests/panic_exit_failure/mod.rs deleted file mode 100644 index b4ac73d1e..000000000 --- a/15_virtual_mem_part2_mmio_remap/tests/panic_exit_failure/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -#[no_mangle] -fn _panic_exit() -> ! { - libkernel::cpu::qemu_exit_failure() -} diff --git a/15_virtual_mem_part2_mmio_remap/tests/panic_exit_success/mod.rs b/15_virtual_mem_part2_mmio_remap/tests/panic_exit_success/mod.rs deleted file mode 100644 index 54bb072d7..000000000 --- a/15_virtual_mem_part2_mmio_remap/tests/panic_exit_success/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2020 Andre Richter - -/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. -#[no_mangle] -fn _panic_exit() -> ! { - libkernel::cpu::qemu_exit_success() -} diff --git a/15_virtual_mem_part2_mmio_remap/tests/runner.rb b/15_virtual_mem_part2_mmio_remap/tests/runner.rb deleted file mode 100755 index 2a0aa393e..000000000 --- a/15_virtual_mem_part2_mmio_remap/tests/runner.rb +++ /dev/null @@ -1,143 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2019-2020 Andre Richter - -require 'English' -require 'pty' - -# Test base class. -class Test - INDENT = ' ' - - def print_border(status) - puts - puts "#{INDENT}-------------------------------------------------------------------" - puts status - puts "#{INDENT}-------------------------------------------------------------------\n\n\n" - end - - def print_error(error) - puts - print_border("#{INDENT}❌ Failure: #{error}: #{@test_name}") - end - - def print_success - print_border("#{INDENT}✅ Success: #{@test_name}") - end - - def print_output - puts "#{INDENT}-------------------------------------------------------------------" - print INDENT - print '🦀 ' - print @output.join.gsub("\n", "\n#{INDENT}") - end - - def finish(error) - print_output - - exit_code = if error - print_error(error) - false - else - print_success - true - end - - exit(exit_code) - end -end - -# Executes tests with console I/O. -class ConsoleTest < Test - def initialize(binary, qemu_cmd, test_name, console_subtests) - super() - - @binary = binary - @qemu_cmd = qemu_cmd - @test_name = test_name - @console_subtests = console_subtests - @cur_subtest = 1 - @output = ["Running #{@console_subtests.length} console-based tests\n", - "-------------------------------------------------------------------\n\n"] - end - - def format_test_name(number, name) - formatted_name = "#{number.to_s.rjust(3)}. #{name}" - formatted_name.ljust(63, '.') - end - - def run_subtest(subtest, qemu_out, qemu_in) - @output << format_test_name(@cur_subtest, subtest.name) - - subtest.run(qemu_out, qemu_in) - - @output << "[ok]\n" - @cur_subtest += 1 - end - - def exec - error = false - - PTY.spawn(@qemu_cmd) do |qemu_out, qemu_in| - begin - @console_subtests.each { |t| run_subtest(t, qemu_out, qemu_in) } - rescue StandardError => e - error = e.message - end - - finish(error) - end - end -end - -# A wrapper around the bare QEMU invocation. -class RawTest < Test - MAX_WAIT_SECS = 5 - - def initialize(binary, qemu_cmd, test_name) - super() - - @binary = binary - @qemu_cmd = qemu_cmd - @test_name = test_name - @output = [] - end - - def exec - error = 'Timed out waiting for test' - io = IO.popen(@qemu_cmd) - - while IO.select([io], nil, nil, MAX_WAIT_SECS) - begin - @output << io.read_nonblock(1024) - rescue EOFError - io.close - error = $CHILD_STATUS.to_i != 0 - break - end - end - - finish(error) - end -end - -##-------------------------------------------------------------------------------------------------- -## Script entry point -##-------------------------------------------------------------------------------------------------- -binary = ARGV.last -test_name = binary.gsub(%r{.*deps/}, '').split('-')[0] -console_test_file = "tests/#{test_name}.rb" -qemu_cmd = ARGV.join(' ') - -test_runner = if File.exist?(console_test_file) - load console_test_file - # subtest_collection is provided by console_test_file - ConsoleTest.new(binary, qemu_cmd, test_name, subtest_collection) - else - RawTest.new(binary, qemu_cmd, test_name) - end - -test_runner.exec diff --git a/15_virtual_mem_part3_precomputed_tables/.cargo/config.toml b/15_virtual_mem_part3_precomputed_tables/.cargo/config.toml new file mode 100644 index 000000000..e34764853 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.'cfg(target_os = "none")'] +runner = "target/kernel_test_runner.sh" diff --git a/15_virtual_mem_part3_precomputed_tables/.vscode/settings.json b/15_virtual_mem_part3_precomputed_tables/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/15_virtual_mem_part3_precomputed_tables/Cargo.lock b/15_virtual_mem_part3_precomputed_tables/Cargo.lock new file mode 100644 index 000000000..1bef088b6 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/Cargo.lock @@ -0,0 +1,84 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.15.0" +dependencies = [ + "aarch64-cpu", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/15_virtual_mem_part3_precomputed_tables/Cargo.toml b/15_virtual_mem_part3_precomputed_tables/Cargo.toml new file mode 100644 index 000000000..6480a7276 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +members = [ + "libraries/*", + "kernel" +] + +[profile.release] +lto = true diff --git a/15_virtual_mem_part3_precomputed_tables/Makefile b/15_virtual_mem_part3_precomputed_tables/Makefile new file mode 100644 index 000000000..bc23270d0 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/Makefile @@ -0,0 +1,354 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF_RAW = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_RAW_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Translation tables +##------------------------------------------------------------------------------ +TT_TOOL_PATH = tools/translation_table_tool + +KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables +KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) + +KERNEL_ELF = $(KERNEL_ELF_TTABLES) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Precompute the kernel translation tables and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) + $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") + @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF_TTABLES) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null + $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/15_virtual_mem_part3_precomputed_tables/README.md b/15_virtual_mem_part3_precomputed_tables/README.md new file mode 100644 index 000000000..989301e0e --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/README.md @@ -0,0 +1,2626 @@ +# Tutorial 15 - Virtual Memory Part 3: Precomputed Translation Tables + +## tl;dr + +- We are making the next baby-steps towards mapping the kernel to the most significant area of the + virtual memory space. +- Instead of dynamically computing the kernel's translation tables during runtime while booting, we + are precomputing them in advance just after kernel compilation, and patch them into the kernel's + binary ahead of time. +- For now, we are still `identity-mapping` the kernel binary. + - However, after this tutorial, we have all the infrastructure in place to easily map it + elsewhere. + +## Table of Contents + +- [Introduction](#introduction) +- [When Load Address != Link Address, Funny Things Can Happen](#when-load-address--link-address-funny-things-can-happen) + * [Interim Conclusion](#interim-conclusion) + * [Doing the Same Thing - Expecting Different Results](#doing-the-same-thing---expecting-different-results) +- [Position-Independent Code (PIC)](#position-independent-code-pic) + * [Using PIC during kernel startup](#using-pic-during-kernel-startup) +- [Precomputed Translation Tables](#precomputed-translation-tables) +- [Implementation](#implementation) + * [Preparing the Kernel Tables](#preparing-the-kernel-tables) + * [Turning on the MMU Before Switching to EL1](#turning-on-the-mmu-before-switching-to-el1) + * [The Translation Table Tool](#the-translation-table-tool) + * [Other changes](#other-changes) +- [Discussion](#discussion) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +This tutorial is another preparatory step for our overall goal of mapping the kernel to the most +significant area of the virtual memory space. + +The reasoning of why we want to do this was given in the previous tutorial's introduction. But lets +for a quick moment think about what it actually means in practice: Currently, the kernel's binary is +loaded by the Raspberry's firmware at address `0x8_0000`. + +In decimal, this address is at `512 KiB`, and therefore well within the _least significant part_ of +the address space. Let's have a look at the picture from the [ARM Cortex-A Series Programmer’s Guide +for ARMv8-A] again to understand in which virtual address space region the kernel would ideally be +mapped to: + +

+ +

+ +As we can see, the architecture proposes somewhere between addresses `0xffff_0000_0000_0000` and +`0xffff_ffff_ffff_ffff`. Once we succeed in mapping the kernel there, the whole lower range between +`0x0` and `0xffff_ffff_ffff` would be free for future applications to use. + +[ARM Cortex-A Series Programmer’s Guide for ARMv8-A]: https://developer.arm.com/documentation/den0024/latest/ + +Now, how can we get there? + +## When Load Address != Link Address, Funny Things Can Happen + +Imagine that, using the linker script, we link the kernel so that its `_start()` function is located +at address `0xffff_0000_0000_0000`. What hasn't changed is that the Raspberry's firmware will still +load the kernel binary at address `0x8_0000`, and the kernel will still start executing from there +with the `MMU` disabled. + +So one of the very first things the kernel must achieve during its boot to function correctly, is to +somehow enable the `MMU` together with `translation tables` that account for the address offset +(`0xffff_0000_0000_0000 -> 0x8_0000`). In previous tutorials, we already generated translation +tables during the kernel's boot, so lets quickly remember how we did that: + +In `src/bsp/__board_name__/memory/mmu.rs` we have a static (or "global" in non-Rust speak) instance +of `struct KernelTranslationTable`: + +```rust +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new()); +``` + +In other parts of the kernel code, this instance would be referenced one way or the other, and its +member functions would be called, for example, when mapping a range of pages. At the end of the day, +after multiple layers of indirection, what happens at the most basic level is that a `piece of code` +manipulates some `global data`. So part of the job of the code is to retrieve the data's constant +address before it can manipulate it. + +Let's simplify the address-retrieval to the most basic code example possible. The example will be +presented as `C` code. Don't ask yet why `C` is chosen. It will get clear as the tutorial develops. + +```c +#include + +uint64_t global_data_word = 0x11223344; + +uint64_t* get_address_of_global(void) { + return &global_data_word; +} +``` + +Let's compile and link this using the following linker script: + +```ld.s +SECTIONS +{ + . = 0x80000; + + .text : { + QUAD(0); /* Intentional fill word */ + QUAD(0); /* Intentional fill word */ + KEEP(*(.text*)) + } + .got : ALIGN(8) { *(.got) } + .data : ALIGN(64K) { + QUAD(0); /* Intentional fill word */ + *(.data*) + } +} +``` + +Here are the compilation steps and the corresponding `objdump` for `AArch64`: + +```console +$ clang --target=aarch64-none-elf -Iinclude -Wall -c start.c -o start.o +$ ld.lld start.o -T kernel.ld -o example.elf +``` + +```c-objdump +Disassembly of section .text: + +0000000000080010 get_address_of_global: + 80010: 80 00 00 90 adrp x0, #0x10000 + 80014: 00 20 00 91 add x0, x0, #0x8 + 80018: c0 03 5f d6 ret + +Disassembly of section .data: + +0000000000090008 global_data_word: + 90008: 44 33 22 11 + 9000c: 00 00 00 00 +``` + +As you can see, the address of function `get_address_of_global()` is `0x8_0010` and +`global_data_word` got address `0x9_0008`. In the function body, the compiler emitted an [`ADRP`] +and `ADD` instruction pair, which means that the global's address is calculated as a `PC-relative +offset`. `PC` means program counter, aka the current position of where the CPU core is currently +executing from. + +Without going in too much detail, what the instruction basically does is: It retrieves the `4 KiB` +page address that belongs to the program counter's (PC) current position (PC is at `0x8_0010`, so +the page address is `0x8_0000`), and adds `0x1_0000`. So after the `ADRP` instruction, register `x0` +holds the value `0x9_0000`. To this value, `8` is added in the next instruction, resulting in the +overall address of `0x9_0008`, which is exactly where `global_data_word` is located. This works, +because after linking a `static executable binary` like we do since `tutorial 01`, relative +positions of code and data are fixed, and not supposed to change during runtime. + +[`ADRP`]: https://developer.arm.com/documentation/dui0802/b/A64-General-Instructions/ADRP + +If the Raspberry's firmware now loads this binary at address `0x8_0000`, as always, we can be sure +that our function returns the correct address of our global data word. + +Now lets link this to the most significant area of memory: + +```ld.s +SECTIONS +{ + . = 0xffff000000000000; /* <--- Only line changed in the linker script! */ + + .text : { + + /* omitted for brevity */ +} +``` + +And compile again: + +```c-objdump +Disassembly of section .text: + +ffff000000000010 get_address_of_global: +ffff000000000010: 80 00 00 90 adrp x0, #0x10000 +ffff000000000014: 00 20 00 91 add x0, x0, #0x8 +ffff000000000018: c0 03 5f d6 ret + +Disassembly of section .data: + +ffff000000010008 global_data_word: +ffff000000010008: 44 33 22 11 +ffff00000001000c: 00 00 00 00 +``` + +And let the Raspberry's firmware load the binary at address `0x8_0000` again (we couldn't load it to +`0xffff_0000_0000_0000` even if we wanted to. That address is `15 Exbibyte`. A Raspberry Pi with +that much RAM won't exist for some time to come 😉). + +Let's try to answer the same question again: Would `get_address_of_global()` return the value for +`global_data_word` that we expect to see (`0xffff_0000_0001_0008` as shown in the objdump)? This +time, the answer is **no**. It would again return `0x9_0008`. + +Why is that? Don't let yourself be distracted by the addresses the `objdump` above is showing. When +the Raspberry's firmware loads this binary at `0x8_0000`, then the Program Counter value when +`get_address_of_global()` executes is again `0x8_0010`. So **the PC-relative calculation** will not +result in the expected value, which would be the **absolute** (alternatively: **link-time**) address +of `global_data_word`. + +### Interim Conclusion + +What have we learned so far? We wrote a little piece of code in a high-level language that retrieves +an address, and we naively expected to retrieve an **absolute** address. + +But compiler and linker conspired against us, and machine code was emitted that uses a PC-relative +addressing scheme, so our expectation is not matched when **load address != link address**. If you +compile for `AArch64`, you'll see relative addressing schemes a lot, because it is natural to the +architecture. + +If you now say: Wait a second, how is this a problem? It actually helps! After all, since the code +is loaded at address `0x8_0000`, this relative addressing scheme will ensure that the processor +accesses the global data word at the correct address! + +Yes, in this particular, constrained demo case, it worked out for us. But have a look at the +following. + +### Doing the Same Thing - Expecting Different Results + +Let's take a quick detour and see what happens if we compile **the exactly same code** for the +`x86_64` processor architecture. First when linked to `0x8_0000`: + +```c-objdump +Disassembly of section .text: + +0000000000080070 get_address_of_global: + 80070: 55 push rbp + 80071: 48 89 e5 mov rbp, rsp + 80074: 48 b8 08 00 09 00 00 00 00 00 movabs rax, 0x90008 + 8007e: 5d pop rbp + 8007f: c3 ret + +Disassembly of section .data: + +ffff000000010008 global_data_word: +ffff000000010008: 44 33 22 11 +ffff00000001000c: 00 00 00 00 +``` + +And now linked to `0xffff_0000_0000_0000`: + +```c-objdump +Disassembly of section .text: + +ffff000000000070 get_address_of_global: +ffff000000000070: 55 push rbp +ffff000000000071: 48 89 e5 mov rbp, rsp +ffff000000000074: 48 b8 08 00 01 00 00 00 ff ff movabs rax, 0xffff000000010008 +ffff00000000007e: 5d pop rbp +ffff00000000007f: c3 ret + +Disassembly of section .data: + +ffff000000010008 global_data_word: +ffff000000010008: 44 33 22 11 +ffff00000001000c: 00 00 00 00 +``` + +Both times, the `movabs` instruction gets emitted. It means that the address is put into the target +register using hardcoded `immediate values`. PC-relative address calculation is not used here. +Hence, this code would return the `absolute` address in both cases. Which means in the second case, +even when the binary would be loaded at `0x8_0000`, the return value would be +`0xffff_0000_0001_0008`. + +**In summary, we get a different result for the same piece of `C` code, depending on the target +processor architecture**. What do we learn from this little detour? + +First, you cannot naively compile and run `Rust` or `C` statically linked binaries when there will +be a **load address != link address** situation. You'll run into undefined behavior very fast. It is +kinda expected and obvious, but hopefully it helped to see it fail in action. + +Furthermore, it is important to understand that there are of course ways to load a symbol's absolute +address into `AArch64` registers using `immediate values` as well. Likewise, you can also do +PC-relative addressing in `x86`. We just looked at a tiny example. Maybe the next line of code would +be compiled into the opposite behavior on the two architectures, so that the `x86` code would do a +PC-relative calculation while the `AArch64` code goes for absolute. + +At the end of the day, what is needed to solve our task at hand (bringup of virtual memory, while +being linked to one address and executing from another), is tight control over the machine +instructions that get emitted for **those pieces of code** that generate the `translation tables` +and enable the `MMU`. + +What we need is called [position-independent code]. + +[position-independent code]: https://en.wikipedia.org/wiki/Position-independent_code + +> Much low-level stuff in this tutorial, isn't it? This was a lot to digest already, but we're far +> from finished. So take a minute or two and clear your mind before we continue. 🧘 + +## Position-Independent Code (PIC) + +As describend by Wikipedia, position-independent code + +> is a body of machine code that, being placed somewhere in the primary memory, **executes +> properly** regardless of its absolute address. + +Your safest bet is to write the pieces that need to be position-independent in `assembly`, because +this gives you full control over when relative or absolute addresses are being generated or used. +You will see this approach often in big projects like the Linux kernel, for example. The downside of +that approach is that the programmer needs good domain knowledge. + +If you feel more adventurous and don't want to go completely without high-level code, you can try to +make use of suitable compiler flags such as `-fpic`, and only use `assembly` where absolutely +needed. Here is the [`-fpic` description for GCC]: + +> -fpic +> +> Generate position-independent code (PIC) suitable for use in a shared library, if supported for +> the target machine. Such code accesses all constant addresses through a global offset table (GOT). +> The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not +> part of GCC; it is part of the operating system). + +[`-fpic` description for GCC]: https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#Code-Gen-Options + +However, it is very important to understand that this flag **is not** a ready-made solution for our +particular problem (and wasn't invented for that case either). There is a hint in the quoted text +above that gives it away: "_The dynamic loader resolves the GOT entries when the program starts (the +dynamic loader is not part of GCC; it is part of the operating system)_". + +Well, we are a booting kernel, and not some (userspace) program running on top of an operating +system. Hence, there is no dynamic loader available. However, it is still possible to benefit from +`-fpic` even in our case. Lets have a look at what happens if we compile the earlier piece of `C` +code for `AArch64` using `-fpic`, still linking the output to the most signifcant part of the memory +space: + +```console +$ clang --target=aarch64-none-elf -Iinclude -Wall -fpic -c start.c -o start.o +$ ld.lld start.o -T kernel.ld -o example.elf +``` + +```c-objdump +Disassembly of section .text: + +ffff000000000010 get_address_of_global: +ffff000000000010: 00 00 00 90 adrp x0, #0x0 +ffff000000000014: 00 28 40 f9 ldr x0, [x0, #0x50] +ffff000000000018: c0 03 5f d6 ret + +Disassembly of section .got: + +ffff000000000050 .got: +ffff000000000050: 08 00 01 00 +ffff000000000054: 00 00 ff ff + +Disassembly of section .data: + +ffff000000010008 global_data_word: +ffff000000010008: 44 33 22 11 +ffff00000001000c: 00 00 00 00 +``` + +What changed compared to earlier is that `get_address_of_global()` now indirects through the `Global +Offset Table`, as has been promised by the compiler's documentation. Specifically, +`get_address_of_global()` addresses the `GOT` using PC-relative addressing (distance from code to +`GOT` must always be fixed), and loads the first 64 bit word from the start of the `GOT`, which +happens to be `0xffff_0000_0001_0008`. + +Okay okay okay... So when we use `-fpic`, we get the **absolute** address of `global_data_word` even +on `AArch64` now. How does this help when the code executes from `0x8_0000`? + +Well, this is the part where the `dynamic loader` quoted above would come into picture if this was a +userspace program: "_The dynamic loader resolves the GOT entries when the program starts_". The +`-fpic` flag is normally used to compile _shared libraries_. Suppose we have a program that uses one +or more shared library. For various reasons, it happens that the shared library is loaded at a +different address than where the userspace program would initially expect it. In our example, +`global_data_word` could be supplied by such a shared library, and the userspace program is only +referencing it. The dynamic loader would know where the shared library was loaded into memory, and +therefore know the real address of `global_data_word`. So before the userspace program starts, the +loader would overwrite the `GOT` entry with the correct location. Et voilà, the compiled high-level +code would execute properly. + +### Using PIC during kernel startup + +If you think about it, our problem is a special case of what we just learned. We have a single +statically linked binary, where everything is dislocated by a fixed offset. In our case, it is +`0xffff_0000_0000_0000 - 0x8_0000 = 0x0fff_efff_ffff8_0000`. If we write some PIC-`assembly` code +which loops over the `GOT` and subtracts `0x0fff_efff_ffff8_0000` from every entry as the very first +thing when our kernel boots, any high-level code compiled with `-fpic` would work correctly +afterwards. + +Moreover, this approach would be portable! Here's the output of our code compiled with `-fpic` for +`x86_64`: + +```c-objdump +Disassembly of section .text: + +ffff000000000070 get_address_of_global: +ffff000000000070: 55 push rbp +ffff000000000071: 48 89 e5 mov rbp, rsp +ffff000000000074: 48 8b 05 2d 00 00 00 mov rax, qword ptr [rip + 0x2d] +ffff00000000007b: 5d pop rbp +ffff00000000007c: c3 ret +ffff00000000007d: 0f 1f 00 nop dword ptr [rax] + +Disassembly of section .got: + +ffff0000000000a8 .got: +ffff0000000000a8: 08 00 01 00 +ffff0000000000ac: 00 00 ff ff + +Disassembly of section .data: + +ffff000000010008 global_data_word: +ffff000000010008: 44 33 22 11 +ffff00000001000c: 00 00 00 00 +``` + +As you can see, the `x86_64` code indirects through the `GOT` now same as the `AArch64` code. + +Of course, indirecting through the `GOT` would be detrimental to performance, so you would restrict +`-fpic` compilation only to the code that is needed to enable the `MMU`. Everything else can be +compiled `non-relocatable` as always, because the translation tables naturally resolve the **load +address != link address** situation once they are live. + +With `C/C++` compilers, this can be done rather easily. The compilers support compilation of +PIC-code on a per-[translation-unit] basis. Think of it as telling the compiler to compile this `.c` +file as `PIC`, but this other `.c` file not. + +[translation-unit]: https://en.wikipedia.org/wiki/Translation_unit_(programming) + +With `Rust`, unfortunately, the [relocation model] can only be set on a per-`crate` basis at the +moment (IINM), so that makes it difficult for us to put this approach to use. + +[relocation model]: https://doc.rust-lang.org/rustc/codegen-options/index.html#relocation-model + +## Precomputed Translation Tables + +As we have just seen, going the `-fpic` way isn't a feasible solution at the time of writing this +text. On the other hand, writing the code to set up the initial page tables in `assembly` isn't that +attractive either, because writing larger pieces of assembly is an error-prone and delicate task. + +Fortunately, there is a third way. We are writing an embedded kernel, and therefore the execution +environment is way more static and deterministic as compared to a general-purpose kernel that can be +deployed on a wide variety of targets. Specifically, for the Raspberrypi, we exactly know the **load +address** of the kernel in advance, and we know about the capabilities of the `MMU`. So there is +nothing stopping us from precomputing the kernel's translation tables ahead of time. + +A disadvantage of this approach is an increased binary size, but this is not a deal breaker in our +case. + +## Implementation + +As stated in the initial `tl;dr`, we're not yet mapping the kernel to the most significant area of +virtual memory. This tutorial will keep the binary `identity-mapped`, and focuses only on the +infrastructure changes which enable the kernel to use `precomputed translation tables`. The actual +switch to high memory will happen in the next tutorial. + +The changes needed are as follows: + +1. Make preparations so that precomputed tables are supported by the kernel's memory subsystem code. +2. Change the boot code of the kernel so that the `MMU` is enabled with the precomputed tables as + soon as possible. +3. Write a `translation table tool` that precomputes the translation tables from the generated + `kernel.elf` file, and patches the tables back into the same. + +### Preparing the Kernel Tables + +The tables must be linked into the `.data` section now so that they become part of the final binary. +This is ensured using an attribute on the table's instance definition in +`bsp/__board_name__/memory/mmu.rs`: + +```rust +#[link_section = ".data"] +#[no_mangle] +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new_for_precompute()); +``` + +The `new_for_precompute()` is a new constructor in the the respective `_arch` code that ensures some +struct members that are not the translation table entries themselves are initialized properly for +the precompute use-case. The additional `#[no_mangle]` is added because we will need to parse the +symbol from the `translation table tool`, and this is easier with unmangled names. + +In the `BSP` code, there is also a new file called `kernel_virt_addr_space_size.ld`, which contains +the kernel's virtual address space size. This file gets included in both, the `kernel.ld` linker +script and `mmu.rs`. We need this value both as a symbol in the kernel's ELF (for the `translation +table tool` to parse it later) and as a constant in the `Rust` code. This inclusion approach is just +a convenience hack that turned out working well. + +One critical parameter that the kernel's boot code needs in order to enable the precomputed tables +is the `translation table base address` which must be programmed into the MMU's `TTBR` register. To +make it accessible easily, it is added to the `.text._start_arguments` section. The definition is +just below the definition of the kernel table instance in the `BSP` code: + +```rust +/// This value is needed during early boot for MMU setup. +/// +/// This will be patched to the correct value by the "translation table tool" after linking. This +/// given value here is just a dummy. +#[link_section = ".text._start_arguments"] +#[no_mangle] +static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; +``` + +### Turning on the MMU Before Switching to EL1 + +Since the Raspberry Pi starts execution in the `EL2` privilege level, one of the first things we do +during boot since `tutorial 09` is to context-switch to the appropriate `EL1`. The `EL2` boot code +is a great place to set up virtual memory for `EL1`. It will allow execution in `EL1` to start with +virtual memory enabled since the very first instruction. The tweaks to `boot.s` are minimal: + +```asm +// Load the base address of the kernel's translation tables. +ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + +// Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. +ADR_REL x1, __boot_core_stack_end_exclusive +mov sp, x1 + +// Jump to Rust code. x0 and x1 hold the function arguments provided to _start_rust(). +b _start_rust +``` + +In addition to the stack's address, we are now reading _the value_ of +`PHYS_KERNEL_TABLES_BASE_ADDR`. The `ldr` instruction addresses the value-to-be-read using a +PC-relative offset, so this is a `position-independent` operation and will therefore be future +proof. The retrieved value is supplied as an argument to function `_start_rust()`, which is defined +in `_arch/__arch_name__/cpu/boot.rs`: + +```rust +#[no_mangle] +pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, + phys_boot_core_stack_end_exclusive_addr: u64, +) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} +``` + +You can also see that we now turn on the `MMU` just before returning to `EL1`. That's basically it +already, the only missing piece that's left is the offline computation of the translation tables. + +### The Translation Table Tool + +The tool for translation table computation is located in the folder +`$ROOT/tools/translation_table_tool`. For ease of use, it is written in `Ruby` 💎. The code is +organized into `BSP` and `arch` parts just like the kernel's `Rust` code, and also has a class for +processing the kernel `ELF` file: + +```console +$ tree tools/translation_table_tool + +tools/translation_table_tool +├── arch.rb +├── bsp.rb +├── generic.rb +├── kernel_elf.rb +└── main.rb + +0 directories, 5 files +``` + +Especially the `arch` part, which deals with compiling the translation table entries, will contain +some overlap with the `Rust` code present in `_arch/aarch64/memory/mmu/translation_table.rs`. It +might have been possible to write this tool in Rust as well, and borrow/share these pieces of code +with the kernel. But in the end, I found it not worth the effort for the few lines of code. + +In the `Makefile`, the tool is invoked after compiling and linking the kernel, and before the +`stripped binary` is generated. It's command line arguments are the target `BSP` type and the path +to the kernel's `ELF` file: + +```Makefile +TT_TOOL_PATH = tools/translation_table_tool + +KERNEL_ELF_RAW = target/$(TARGET)/release/kernel +# [...] + +KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables +# [...] + +EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb +# [...] + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Precompute the kernel translation tables and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) + $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") + @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(TARGET) $(BSP) $(KERNEL_ELF_TTABLES) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF_TTABLES) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) +``` + +In `main.rb`, the `KERNEL_ELF` instance for handling the `ELF` file is created first, followed by +`BSP` and `arch` parts: + +```ruby +KERNEL_ELF = KernelELF.new(kernel_elf_path) + +BSP = case BSP_TYPE + when :rpi3, :rpi4 + RaspberryPi.new + else + raise + end + +TRANSLATION_TABLES = case KERNEL_ELF.machine + when :AArch64 + Arch::ARMv8::TranslationTable.new + else + raise + end + +kernel_map_binary +``` + +Finally, the function `kernel_map_binary` is called, which kicks of a sequence of interactions +between the `KERNEL_ELF`, `BSP` and `TRANSLATION_TABLES` instances: + +```ruby +def kernel_map_binary + mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors + + # omitted + + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' + puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end + + # omitted +end +``` + +The `generate_mapping_descriptors` method internally uses the +[rbelftools](https://github.com/david942j/rbelftools) gem to parse the kernel's `ELF`. It extracts +information about the various segments that comprise the kernel, as well as segment characteristics +like their `virtual` and `physical` addresses (aka the mapping; still identity-mapped in this case) +and the memory attributes. + +Part of this information can be cross-checked using the `make readelf` target if you're curious: + +```console +$ make readelf + +Program Headers: + Type Offset VirtAddr PhysAddr + FileSiz MemSiz Flags Align + LOAD 0x0000000000010000 0x0000000000000000 0x0000000000000000 + 0x0000000000000000 0x0000000000080000 RW 0x10000 + LOAD 0x0000000000010000 0x0000000000080000 0x0000000000080000 + 0x000000000000cae8 0x000000000000cae8 R E 0x10000 + LOAD 0x0000000000020000 0x0000000000090000 0x0000000000090000 + 0x0000000000030dc0 0x0000000000030de0 RW 0x10000 + + Section to Segment mapping: + Segment Sections... + 00 .boot_core_stack + 01 .text .rodata + 02 .data .bss + +``` + +The output of `generate_mapping_descriptors` is then fed into the `map_at()` method of the +`TRANSLATION_TABLE` instance. For it to work properly, `TRANSLATION_TABLE` needs knowledge about +**location** and **layout** of the kernel's table structure. Location will be queried from the `BSP` +code, which itself retrieves it by querying `KERNEL_ELF` for the `BSP`-specific `KERNEL_TABLES` +symbol. The layout, on the other hand, is hardcoded and as such must be kept in sync with the +structure definition in `translation_tables.rs`. + +Finally, after the mappings have been created, it is time to _patch_ them back into the kernel ELF +file. This is initiated from `main.rb` again: + +```ruby +kernel_patch_tables(kernel_elf_path) +kernel_patch_base_addr(kernel_elf_path) +``` + +The tool prints some information on the fly. Here's the console output of a successful run: + +```console +$ make + +Compiling kernel - rpi3 + Finished release [optimized] target(s) in 0.00s + +Precomputing kernel translation tables and patching kernel ELF + ------------------------------------------------------------------------------------ + Sections Virt Start Addr Phys Start Addr Size Attr + ------------------------------------------------------------------------------------ + Generating .boot_core_stack | 0x0000_0000_0000_0000 | 0x0000_0000_0000_0000 | 512 KiB | C RW XN + Generating .text .rodata | 0x0000_0000_0008_0000 | 0x0000_0000_0008_0000 | 64 KiB | C RO X + Generating .data .bss | 0x0000_0000_0009_0000 | 0x0000_0000_0009_0000 | 256 KiB | C RW XN + ------------------------------------------------------------------------------------ + Patching Kernel table struct at ELF file offset 0x2_0000 + Patching Kernel tables physical base address start argument to value 0xb_0000 at ELF file offset 0x1_0068 + Finished in 0.16s + +``` + +Please note how **only** the kernel binary is precomputed! Thanks to the changes made in the last +tutorial, anything else, like `MMIO-remapping`, can and will happen lazily during runtime. + +### Other changes + +Two more things that changed in this tutorial, but won't be explained in detail: + +- Since virtual memory in `EL1` is now active from the start, any attempt to convert from a kernel + `Address` to `Address` is now done using the function + `mmu::try_kernel_virt_addr_to_phys_addr()`, which internally uses a new function that has been + added to the `TranslationTable` interface. If there is no valid virtual-to-physical mapping + present in the tables, an `Err()` is returned. +- The precomputed translation table mappings won't automatically have entries in the kernel's + `mapping info record`, which is used to print mapping info during boot. Mapping record entries are + not computed offline in order to reduce complexity. For this reason, the `BSP` code, which in + earlier tutorials would have called `kernel_map_at()` (which implicitly would have generated + mapping record entries), now only calls `kernel_add_mapping_record()`, since the mappings are + already in place. + +## Discussion + +It is understood that there is room for optimizations in the presented approach. For example, the +generated kernel binary contains the _complete_ array of translation tables for the whole kernel +virtual address space. However, most of the entries are empty initially, because the kernel binary +only occupies a small area in the tables. It would make sense to add some smarts so that only the +non-zero entries are packed into binary. + +On the other hand, this would add complexity to the code. The increased size doesn't hurt too much +yet, so the reduced complexity in the code is a tradeoff made willingly to keep everything concise +and focused on the high-level concepts. + +## Test it + +```console +$ make chainboot +[...] + +Precomputing kernel translation tables and patching kernel ELF + ------------------------------------------------------------------------------------ + Sections Virt Start Addr Phys Start Addr Size Attr + ------------------------------------------------------------------------------------ + Generating .boot_core_stack | 0x0000_0000_0000_0000 | 0x0000_0000_0000_0000 | 512 KiB | C RW XN + Generating .text .rodata | 0x0000_0000_0008_0000 | 0x0000_0000_0008_0000 | 64 KiB | C RO X + Generating .data .bss | 0x0000_0000_0009_0000 | 0x0000_0000_0009_0000 | 256 KiB | C RW XN + ------------------------------------------------------------------------------------ + Patching Kernel table struct at ELF file offset 0x2_0000 + Patching Kernel tables physical base address start argument to value 0xb_0000 at ELF file offset 0x1_0068 + Finished in 0.15s + +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 +[ML] Loaded! Executing the payload now + +[ 2.866917] mingo version 0.15.0 +[ 2.867125] Booting on: Raspberry Pi 3 +[ 2.867580] MMU online: +[ 2.867872] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 2.869616] Virtual Physical Size Attr Entity +[ 2.871360] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 2.873105] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack +[ 2.874709] 0x0000_0000_0008_0000..0x0000_0000_0008_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data +[ 2.876322] 0x0000_0000_0009_0000..0x0000_0000_000c_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss +[ 2.877893] 0x0000_0000_000d_0000..0x0000_0000_000d_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART +[ 2.879410] | BCM GPIO +[ 2.880861] 0x0000_0000_000e_0000..0x0000_0000_000e_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Interrupt Controller +[ 2.882487] ------------------------------------------------------------------------------------------------------------------------------------------- +``` + +## Diff to previous +```diff + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml +--- 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml ++++ 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.14.0" ++version = "0.15.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs +@@ -11,6 +11,7 @@ + //! + //! crate::cpu::boot::arch_boot + ++use crate::{memory, memory::Address}; + use aarch64_cpu::{asm, registers::*}; + use core::arch::global_asm; + use tock_registers::interfaces::Writeable; +@@ -75,9 +76,16 @@ + /// + /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. + #[no_mangle] +-pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { ++pub unsafe extern "C" fn _start_rust( ++ phys_kernel_tables_base_addr: u64, ++ phys_boot_core_stack_end_exclusive_addr: u64, ++) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + ++ // Turn on the MMU for EL1. ++ let addr = Address::new(phys_kernel_tables_base_addr as usize); ++ memory::mmu::enable_mmu_and_caching(addr).unwrap(); ++ + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() + } + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s +--- 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s +@@ -53,19 +53,22 @@ + + // Prepare the jump to Rust code. + .L_prepare_rust: ++ // Load the base address of the kernel's translation tables. ++ ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs ++ + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. +- ADR_REL x0, __boot_core_stack_end_exclusive +- mov sp, x0 ++ ADR_REL x1, __boot_core_stack_end_exclusive ++ mov sp, x1 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. +- ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs +- mrs x2, CNTFRQ_EL0 +- cmp x2, xzr ++ ADR_REL x2, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs ++ mrs x3, CNTFRQ_EL0 ++ cmp x3, xzr + b.eq .L_parking_loop +- str w2, [x1] ++ str w3, [x2] + +- // Jump to Rust code. x0 holds the function argument provided to _start_rust(). ++ // Jump to Rust code. x0 and x1 hold the function arguments provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +@@ -125,7 +125,7 @@ + } + + trait StartAddr { +- fn phys_start_addr(&self) -> Address; ++ fn virt_start_addr(&self) -> Address; + } + + //-------------------------------------------------------------------------------------------------- +@@ -151,9 +151,8 @@ + // Private Code + //-------------------------------------------------------------------------------------------------- + +-// The binary is still identity mapped, so we don't need to convert here. + impl StartAddr for [T; N] { +- fn phys_start_addr(&self) -> Address { ++ fn virt_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) + } + } +@@ -218,6 +217,35 @@ + } + } + ++/// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. ++impl convert::TryFrom> for AttributeFields { ++ type Error = &'static str; ++ ++ fn try_from( ++ desc: InMemoryRegister, ++ ) -> Result { ++ let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { ++ memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, ++ memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, ++ _ => return Err("Unexpected memory attribute"), ++ }; ++ ++ let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { ++ Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, ++ Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, ++ _ => return Err("Unexpected access permission"), ++ }; ++ ++ let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; ++ ++ Ok(AttributeFields { ++ mem_attributes, ++ acc_perms, ++ execute_never, ++ }) ++ } ++} ++ + impl PageDescriptor { + /// Create an instance. + /// +@@ -250,6 +278,19 @@ + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } ++ ++ /// Returns the output page. ++ fn output_page_addr(&self) -> PageAddress { ++ let shifted = InMemoryRegister::::new(self.value) ++ .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; ++ ++ PageAddress::from(shifted << Granule64KiB::SHIFT) ++ } ++ ++ /// Returns the attributes. ++ fn try_attributes(&self) -> Result { ++ InMemoryRegister::::new(self.value).try_into() ++ } + } + + //-------------------------------------------------------------------------------------------------- +@@ -267,7 +308,7 @@ + impl FixedSizeTranslationTable { + /// Create an instance. + #[allow(clippy::assertions_on_constants)] +- pub const fn new() -> Self { ++ const fn _new(for_precompute: bool) -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + + // Can't have a zero-sized address space. +@@ -276,10 +317,19 @@ + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], +- initialized: false, ++ initialized: for_precompute, + } + } + ++ pub const fn new_for_precompute() -> Self { ++ Self::_new(true) ++ } ++ ++ #[cfg(test)] ++ pub fn new_for_runtime() -> Self { ++ Self::_new(false) ++ } ++ + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( +@@ -297,6 +347,18 @@ + Ok((lvl2_index, lvl3_index)) + } + ++ /// Returns the PageDescriptor corresponding to the supplied page address. ++ #[inline(always)] ++ fn page_descriptor_from_page_addr( ++ &self, ++ virt_page_addr: PageAddress, ++ ) -> Result<&PageDescriptor, &'static str> { ++ let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; ++ let desc = &self.lvl3[lvl2_index][lvl3_index]; ++ ++ Ok(desc) ++ } ++ + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. +@@ -325,24 +387,23 @@ + impl memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable + { +- fn init(&mut self) { ++ fn init(&mut self) -> Result<(), &'static str> { + if self.initialized { +- return; ++ return Ok(()); + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { +- let phys_table_addr = self.lvl3[lvl2_nr].phys_start_addr(); ++ let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); ++ let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; +- } + +- fn phys_base_address(&self) -> Address { +- self.lvl2.phys_start_addr() ++ Ok(()) + } + + unsafe fn map_at( +@@ -372,6 +433,45 @@ + + Ok(()) + } ++ ++ fn try_virt_page_addr_to_phys_page_addr( ++ &self, ++ virt_page_addr: PageAddress, ++ ) -> Result, &'static str> { ++ let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; ++ ++ if !page_desc.is_valid() { ++ return Err("Page marked invalid"); ++ } ++ ++ Ok(page_desc.output_page_addr()) ++ } ++ ++ fn try_page_attributes( ++ &self, ++ virt_page_addr: PageAddress, ++ ) -> Result { ++ let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; ++ ++ if !page_desc.is_valid() { ++ return Err("Page marked invalid"); ++ } ++ ++ page_desc.try_attributes() ++ } ++ ++ /// Try to translate a virtual address to a physical address. ++ /// ++ /// Will only succeed if there exists a valid mapping for the input address. ++ fn try_virt_addr_to_phys_addr( ++ &self, ++ virt_addr: Address, ++ ) -> Result, &'static str> { ++ let virt_page = PageAddress::from(virt_addr.align_down_page()); ++ let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; ++ ++ Ok(phys_page.into_inner() + virt_addr.offset_into_page()) ++ } + } + + //-------------------------------------------------------------------------------------------------- + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld +--- 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld +@@ -3,6 +3,8 @@ + * Copyright (c) 2018-2023 Andre Richter + */ + ++INCLUDE kernel_virt_addr_space_size.ld; ++ + PAGE_SIZE = 64K; + PAGE_MASK = PAGE_SIZE - 1; + +@@ -89,7 +91,7 @@ + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + +- ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") ++ ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Misc + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld +--- 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld +@@ -0,0 +1 @@ ++__kernel_virt_addr_space_size = 1024 * 1024 * 1024 + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs +@@ -7,8 +7,8 @@ + use crate::{ + memory::{ + mmu::{ +- self as generic_mmu, AccessPermissions, AddressSpace, AssociatedTranslationTable, +- AttributeFields, MemAttributes, MemoryRegion, PageAddress, TranslationGranule, ++ self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, ++ MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, +@@ -31,7 +31,7 @@ + pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + + /// The kernel's virtual address space defined by this BSP. +-pub type KernelVirtAddrSpace = AddressSpace<{ 1024 * 1024 * 1024 }>; ++pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; + + //-------------------------------------------------------------------------------------------------- + // Global instances +@@ -43,13 +43,35 @@ + /// + /// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. + /// There is a unit tests that checks this porperty. ++#[link_section = ".data"] ++#[no_mangle] + static KERNEL_TABLES: InitStateLock = +- InitStateLock::new(KernelTranslationTable::new()); ++ InitStateLock::new(KernelTranslationTable::new_for_precompute()); ++ ++/// This value is needed during early boot for MMU setup. ++/// ++/// This will be patched to the correct value by the "translation table tool" after linking. This ++/// given value here is just a dummy. ++#[link_section = ".text._start_arguments"] ++#[no_mangle] ++static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; + + //-------------------------------------------------------------------------------------------------- + // Private Code + //-------------------------------------------------------------------------------------------------- + ++/// This is a hack for retrieving the value for the kernel's virtual address space size as a ++/// constant from a common place, since it is needed as a compile-time/link-time constant in both, ++/// the linker script and the Rust sources. ++#[allow(clippy::needless_late_init)] ++const fn kernel_virt_addr_space_size() -> usize { ++ let __kernel_virt_addr_space_size; ++ ++ include!("../kernel_virt_addr_space_size.ld"); ++ ++ __kernel_virt_addr_space_size ++} ++ + /// Helper function for calculating the number of pages the given parameter spans. + const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); +@@ -88,18 +110,22 @@ + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) + } + +-// The binary is still identity mapped, so use this trivial conversion function for mapping below. +- ++// There is no reason to expect the following conversions to fail, since they were generated offline ++// by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. + fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { +- MemoryRegion::new( +- PageAddress::from(virt_region.start_page_addr().into_inner().as_usize()), +- PageAddress::from( +- virt_region +- .end_exclusive_page_addr() +- .into_inner() +- .as_usize(), +- ), +- ) ++ let phys_start_page_addr = ++ generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) ++ .unwrap(); ++ ++ let phys_end_exclusive_page_addr = phys_start_page_addr ++ .checked_offset(virt_region.num_pages() as isize) ++ .unwrap(); ++ ++ MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) ++} ++ ++fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { ++ generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() + } + + //-------------------------------------------------------------------------------------------------- +@@ -121,109 +147,33 @@ + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) + } + +-/// Map the kernel binary. ++/// Add mapping records for the kernel binary. + /// +-/// # Safety +-/// +-/// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking. +-pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { +- generic_mmu::kernel_map_at( ++/// The actual translation table entries for the kernel binary are generated using the offline ++/// `translation table tool` and patched into the kernel binary. This function just adds the mapping ++/// record entries. ++pub fn kernel_add_mapping_records_for_precomputed() { ++ let virt_boot_core_stack_region = virt_boot_core_stack_region(); ++ generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", +- &virt_boot_core_stack_region(), +- &kernel_virt_to_phys_region(virt_boot_core_stack_region()), +- &AttributeFields { +- mem_attributes: MemAttributes::CacheableDRAM, +- acc_perms: AccessPermissions::ReadWrite, +- execute_never: true, +- }, +- )?; ++ &virt_boot_core_stack_region, ++ &kernel_virt_to_phys_region(virt_boot_core_stack_region), ++ &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), ++ ); + +- generic_mmu::kernel_map_at( ++ let virt_code_region = virt_code_region(); ++ generic_mmu::kernel_add_mapping_record( + "Kernel code and RO data", +- &virt_code_region(), +- &kernel_virt_to_phys_region(virt_code_region()), +- &AttributeFields { +- mem_attributes: MemAttributes::CacheableDRAM, +- acc_perms: AccessPermissions::ReadOnly, +- execute_never: false, +- }, +- )?; ++ &virt_code_region, ++ &kernel_virt_to_phys_region(virt_code_region), ++ &kernel_page_attributes(virt_code_region.start_page_addr()), ++ ); + +- generic_mmu::kernel_map_at( ++ let virt_data_region = virt_data_region(); ++ generic_mmu::kernel_add_mapping_record( + "Kernel data and bss", +- &virt_data_region(), +- &kernel_virt_to_phys_region(virt_data_region()), +- &AttributeFields { +- mem_attributes: MemAttributes::CacheableDRAM, +- acc_perms: AccessPermissions::ReadWrite, +- execute_never: true, +- }, +- )?; +- +- Ok(()) +-} +- +-//-------------------------------------------------------------------------------------------------- +-// Testing +-//-------------------------------------------------------------------------------------------------- +- +-#[cfg(test)] +-mod tests { +- use super::*; +- use core::{cell::UnsafeCell, ops::Range}; +- use test_macros::kernel_test; +- +- /// Check alignment of the kernel's virtual memory layout sections. +- #[kernel_test] +- fn virt_mem_layout_sections_are_64KiB_aligned() { +- for i in [ +- virt_boot_core_stack_region, +- virt_code_region, +- virt_data_region, +- ] +- .iter() +- { +- let start = i().start_page_addr().into_inner(); +- let end_exclusive = i().end_exclusive_page_addr().into_inner(); +- +- assert!(start.is_page_aligned()); +- assert!(end_exclusive.is_page_aligned()); +- assert!(end_exclusive >= start); +- } +- } +- +- /// Ensure the kernel's virtual memory layout is free of overlaps. +- #[kernel_test] +- fn virt_mem_layout_has_no_overlaps() { +- let layout = [ +- virt_boot_core_stack_region(), +- virt_code_region(), +- virt_data_region(), +- ]; +- +- for (i, first_range) in layout.iter().enumerate() { +- for second_range in layout.iter().skip(i + 1) { +- assert!(!first_range.overlaps(second_range)) +- } +- } +- } +- +- /// Check if KERNEL_TABLES is in .bss. +- #[kernel_test] +- fn kernel_tables_in_bss() { +- extern "Rust" { +- static __bss_start: UnsafeCell; +- static __bss_end_exclusive: UnsafeCell; +- } +- +- let bss_range = unsafe { +- Range { +- start: __bss_start.get(), +- end: __bss_end_exclusive.get(), +- } +- }; +- let kernel_tables_addr = &KERNEL_TABLES as *const _ as usize as *mut u64; +- +- assert!(bss_range.contains(&kernel_tables_addr)); +- } ++ &virt_data_region, ++ &kernel_virt_to_phys_region(virt_data_region), ++ &kernel_page_attributes(virt_data_region.start_page_addr()), ++ ); + } + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs +@@ -187,17 +187,7 @@ + #[no_mangle] + unsafe fn kernel_init() -> ! { + exception::handling_init(); +- +- let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { +- Err(string) => panic!("Error mapping kernel binary: {}", string), +- Ok(addr) => addr, +- }; +- +- if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { +- panic!("Enabling MMU failed: {}", e); +- } +- +- memory::mmu::post_enable_init(); ++ memory::init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/main.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/main.rs +@@ -17,27 +17,16 @@ + + /// Early init code. + /// ++/// When this code runs, virtual memory is already enabled. ++/// + /// # Safety + /// + /// - Only a single core must be active and running this function. +-/// - The init calls in this function must appear in the correct order: +-/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, +-/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ +-/// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. ++/// - Printing will not work until the respective driver's MMIO is remapped. + #[no_mangle] + unsafe fn kernel_init() -> ! { + exception::handling_init(); +- +- let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { +- Err(string) => panic!("Error mapping kernel binary: {}", string), +- Ok(addr) => addr, +- }; +- +- if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { +- panic!("Enabling MMU failed: {}", e); +- } +- +- memory::mmu::post_enable_init(); ++ memory::init(); + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { +@@ -47,6 +36,8 @@ + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + ++ bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); ++ + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs +@@ -23,6 +23,8 @@ + + /// Translation table interfaces. + pub mod interface { ++ use crate::memory::mmu::PageAddress; ++ + use super::*; + + /// Translation table operations. +@@ -33,10 +35,7 @@ + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. +- fn init(&mut self); +- +- /// The translation table's base address to be used for programming the MMU. +- fn phys_base_address(&self) -> Address; ++ fn init(&mut self) -> Result<(), &'static str>; + + /// Map the given virtual memory region to the given physical memory region. + /// +@@ -53,6 +52,30 @@ + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; ++ ++ /// Try to translate a virtual page address to a physical page address. ++ /// ++ /// Will only succeed if there exists a valid mapping for the input page. ++ fn try_virt_page_addr_to_phys_page_addr( ++ &self, ++ virt_page_addr: PageAddress, ++ ) -> Result, &'static str>; ++ ++ /// Try to get the attributes of a page. ++ /// ++ /// Will only succeed if there exists a valid mapping for the input page. ++ fn try_page_attributes( ++ &self, ++ virt_page_addr: PageAddress, ++ ) -> Result; ++ ++ /// Try to translate a virtual address to a physical address. ++ /// ++ /// Will only succeed if there exists a valid mapping for the input address. ++ fn try_virt_addr_to_phys_addr( ++ &self, ++ virt_addr: Address, ++ ) -> Result, &'static str>; + } + } + +@@ -72,9 +95,9 @@ + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. +- let mut tables = MinSizeTranslationTable::new(); ++ let mut tables = MinSizeTranslationTable::new_for_runtime(); + +- tables.init(); ++ assert_eq!(tables.init(), Ok(())); + + let virt_start_page_addr: PageAddress = PageAddress::from(0); + let virt_end_exclusive_page_addr: PageAddress = +@@ -94,5 +117,21 @@ + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; ++ ++ assert_eq!( ++ tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), ++ Ok(phys_start_page_addr) ++ ); ++ ++ assert_eq!( ++ tables.try_page_attributes(virt_start_page_addr.checked_offset(6).unwrap()), ++ Err("Page marked invalid") ++ ); ++ ++ assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); ++ ++ let virt_addr = virt_start_page_addr.into_inner() + 0x100; ++ let phys_addr = phys_start_page_addr.into_inner() + 0x100; ++ assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); + } + } + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs +@@ -16,7 +16,8 @@ + use crate::{ + bsp, + memory::{Address, Physical, Virtual}, +- synchronization, warn, ++ synchronization::{self, interface::Mutex}, ++ warn, + }; + use core::{fmt, num::NonZeroUsize}; + +@@ -73,17 +74,9 @@ + // Private Code + //-------------------------------------------------------------------------------------------------- + use interface::MMU; +-use synchronization::interface::*; ++use synchronization::interface::ReadWriteEx; + use translation_table::interface::TranslationTable; + +-/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +-/// MMIO VA allocator with it. +-fn kernel_init_mmio_va_allocator() { +- let region = bsp::memory::mmu::virt_mmio_remap_region(); +- +- page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +-} +- + /// Map a region in the kernel's translation tables. + /// + /// No input checks done, input is passed through to the architectural implementation. +@@ -101,13 +94,21 @@ + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + +- if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { +- warn!("{}", x); +- } ++ kernel_add_mapping_record(name, virt_region, phys_region, attr); + + Ok(()) + } + ++/// Try to translate a kernel virtual address to a physical address. ++/// ++/// Will only succeed if there exists a valid mapping for the input address. ++fn try_kernel_virt_addr_to_phys_addr( ++ virt_addr: Address, ++) -> Result, &'static str> { ++ bsp::memory::mmu::kernel_translation_tables() ++ .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) ++} ++ + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -155,27 +156,24 @@ + } + } + +-/// Raw mapping of a virtual to physical region in the kernel translation tables. +-/// +-/// Prevents mapping into the MMIO range of the tables. +-/// +-/// # Safety +-/// +-/// - See `kernel_map_at_unchecked()`. +-/// - Does not prevent aliasing. Currently, the callers must be trusted. +-pub unsafe fn kernel_map_at( ++/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's ++/// MMIO VA allocator with it. ++pub fn kernel_init_mmio_va_allocator() { ++ let region = bsp::memory::mmu::virt_mmio_remap_region(); ++ ++ page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); ++} ++ ++/// Add an entry to the mapping info record. ++pub fn kernel_add_mapping_record( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +-) -> Result<(), &'static str> { +- if bsp::memory::mmu::virt_mmio_remap_region().overlaps(virt_region) { +- return Err("Attempt to manually map into MMIO region"); ++) { ++ if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { ++ warn!("{}", x); + } +- +- kernel_map_at_unchecked(name, virt_region, phys_region, attr)?; +- +- Ok(()) + } + + /// MMIO remapping in the kernel translation tables. +@@ -224,21 +222,29 @@ + Ok(virt_addr + offset_into_start_page) + } + +-/// Map the kernel's binary. Returns the translation table's base address. +-/// +-/// # Safety ++/// Try to translate a kernel virtual page address to a physical page address. + /// +-/// - See [`bsp::memory::mmu::kernel_map_binary()`]. +-pub unsafe fn kernel_map_binary() -> Result, &'static str> { +- let phys_kernel_tables_base_addr = +- bsp::memory::mmu::kernel_translation_tables().write(|tables| { +- tables.init(); +- tables.phys_base_address() +- }); ++/// Will only succeed if there exists a valid mapping for the input page. ++pub fn try_kernel_virt_page_addr_to_phys_page_addr( ++ virt_page_addr: PageAddress, ++) -> Result, &'static str> { ++ bsp::memory::mmu::kernel_translation_tables() ++ .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) ++} + +- bsp::memory::mmu::kernel_map_binary()?; ++/// Try to get the attributes of a kernel page. ++/// ++/// Will only succeed if there exists a valid mapping for the input page. ++pub fn try_kernel_page_attributes( ++ virt_page_addr: PageAddress, ++) -> Result { ++ bsp::memory::mmu::kernel_translation_tables() ++ .read(|tables| tables.try_page_attributes(virt_page_addr)) ++} + +- Ok(phys_kernel_tables_base_addr) ++/// Human-readable print of all recorded kernel mappings. ++pub fn kernel_print_mappings() { ++ mapping_record::kernel_print() + } + + /// Enable the MMU and data + instruction caching. +@@ -246,56 +252,9 @@ + /// # Safety + /// + /// - Crucial function during kernel init. Changes the the complete memory view of the processor. ++#[inline(always)] + pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) + } +- +-/// Finish initialization of the MMU subsystem. +-pub fn post_enable_init() { +- kernel_init_mmio_va_allocator(); +-} +- +-/// Human-readable print of all recorded kernel mappings. +-pub fn kernel_print_mappings() { +- mapping_record::kernel_print() +-} +- +-//-------------------------------------------------------------------------------------------------- +-// Testing +-//-------------------------------------------------------------------------------------------------- +- +-#[cfg(test)] +-mod tests { +- use super::*; +- use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; +- use test_macros::kernel_test; +- +- /// Check that you cannot map into the MMIO VA range from kernel_map_at(). +- #[kernel_test] +- fn no_manual_mmio_map() { +- let phys_start_page_addr: PageAddress = PageAddress::from(0); +- let phys_end_exclusive_page_addr: PageAddress = +- phys_start_page_addr.checked_offset(5).unwrap(); +- let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); +- +- let num_pages = NonZeroUsize::new(phys_region.num_pages()).unwrap(); +- let virt_region = page_alloc::kernel_mmio_va_allocator() +- .lock(|allocator| allocator.alloc(num_pages)) +- .unwrap(); +- +- let attr = AttributeFields { +- mem_attributes: MemAttributes::CacheableDRAM, +- acc_perms: AccessPermissions::ReadWrite, +- execute_never: true, +- }; +- +- unsafe { +- assert_eq!( +- kernel_map_at("test", &virt_region, &phys_region, &attr), +- Err("Attempt to manually map into MMIO region") +- ) +- }; +- } +-} + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs +@@ -136,6 +136,11 @@ + } + } + ++/// Initialize the memory subsystem. ++pub fn init() { ++ mmu::kernel_init_mmio_va_allocator(); ++} ++ + //-------------------------------------------------------------------------------------------------- + // Testing + //-------------------------------------------------------------------------------------------------- + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs +@@ -18,17 +18,7 @@ + use console::console; + + exception::handling_init(); +- +- let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { +- Err(string) => panic!("Error mapping kernel binary: {}", string), +- Ok(addr) => addr, +- }; +- +- if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { +- panic!("Enabling MMU failed: {}", e); +- } +- +- memory::mmu::post_enable_init(); ++ memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs +@@ -17,17 +17,7 @@ + #[no_mangle] + unsafe fn kernel_init() -> ! { + exception::handling_init(); +- +- let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { +- Err(string) => panic!("Error mapping kernel binary: {}", string), +- Ok(addr) => addr, +- }; +- +- if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { +- panic!("Enabling MMU failed: {}", e); +- } +- +- memory::mmu::post_enable_init(); ++ memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs +@@ -22,26 +22,12 @@ + #[no_mangle] + unsafe fn kernel_init() -> ! { + exception::handling_init(); ++ memory::init(); ++ bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + +- let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { +- Err(string) => { +- info!("Error mapping kernel binary: {}", string); +- cpu::qemu_exit_failure() +- } +- Ok(addr) => addr, +- }; +- +- if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { +- info!("Enabling MMU failed: {}", e); +- cpu::qemu_exit_failure() +- } +- +- memory::mmu::post_enable_init(); +- bsp::driver::qemu_bring_up_console(); +- + info!("Writing beyond mapped area to address 9 GiB..."); + let big_addr: u64 = 9 * 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs +@@ -31,26 +31,12 @@ + #[no_mangle] + unsafe fn kernel_init() -> ! { + exception::handling_init(); ++ memory::init(); ++ bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + +- let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { +- Err(string) => { +- info!("Error mapping kernel binary: {}", string); +- cpu::qemu_exit_failure() +- } +- Ok(addr) => addr, +- }; +- +- if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { +- info!("Enabling MMU failed: {}", e); +- cpu::qemu_exit_failure() +- } +- +- memory::mmu::post_enable_init(); +- bsp::driver::qemu_bring_up_console(); +- + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + +diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs +--- 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs ++++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs +@@ -15,20 +15,10 @@ + + #[no_mangle] + unsafe fn kernel_init() -> ! { +- exception::handling_init(); +- +- let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { +- Err(string) => panic!("Error mapping kernel binary: {}", string), +- Ok(addr) => addr, +- }; +- +- if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { +- panic!("Enabling MMU failed: {}", e); +- } +- +- memory::mmu::post_enable_init(); ++ memory::init(); + bsp::driver::qemu_bring_up_console(); + ++ exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + +diff -uNr 14_virtual_mem_part2_mmio_remap/Makefile 15_virtual_mem_part3_precomputed_tables/Makefile +--- 14_virtual_mem_part2_mmio_remap/Makefile ++++ 15_virtual_mem_part3_precomputed_tables/Makefile +@@ -72,10 +72,20 @@ + KERNEL_LINKER_SCRIPT = kernel.ld + LAST_BUILD_CONFIG = target/$(BSP).build_config + +-KERNEL_ELF = target/$(TARGET)/release/kernel ++KERNEL_ELF_RAW = target/$(TARGET)/release/kernel + # This parses cargo's dep-info file. + # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +-KERNEL_ELF_DEPS = $(filter-out modulo: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ++KERNEL_ELF_RAW_DEPS = $(filter-out modulo: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ++ ++##------------------------------------------------------------------------------ ++## Translation tables ++##------------------------------------------------------------------------------ ++TT_TOOL_PATH = tools/translation_table_tool ++ ++KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables ++KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) ++ ++KERNEL_ELF = $(KERNEL_ELF_TTABLES) + + + +@@ -104,6 +114,7 @@ + -O binary + + EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) ++EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb + EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb + EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +@@ -154,16 +165,24 @@ + ##------------------------------------------------------------------------------ + ## Compile the kernel ELF + ##------------------------------------------------------------------------------ +-$(KERNEL_ELF): $(KERNEL_ELF_DEPS) ++$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + + ##------------------------------------------------------------------------------ ++## Precompute the kernel translation tables and patch them into the kernel ELF ++##------------------------------------------------------------------------------ ++$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) ++ $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") ++ @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) ++ @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) ++ ++##------------------------------------------------------------------------------ + ## Generate the stripped kernel binary + ##------------------------------------------------------------------------------ +-$(KERNEL_BIN): $(KERNEL_ELF) ++$(KERNEL_BIN): $(KERNEL_ELF_TTABLES) + $(call color_header, "Generating stripped binary") +- @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) ++ @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") +@@ -301,6 +320,7 @@ + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + ++ $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null + $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY + endef + +diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/arch.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb +--- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/arch.rb ++++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb +@@ -0,0 +1,312 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2021-2023 Andre Richter ++ ++# Bitfield manipulation. ++class BitField ++ def initialize ++ @value = 0 ++ end ++ ++ def self.attr_bitfield(name, offset, num_bits) ++ define_method("#{name}=") do |bits| ++ mask = (2**num_bits) - 1 ++ ++ raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? ++ ++ # Clear bitfield ++ @value &= ~(mask << offset) ++ ++ # Set it ++ @value |= (bits << offset) ++ end ++ end ++ ++ def to_i ++ @value ++ end ++ ++ def size_in_byte ++ 8 ++ end ++end ++ ++# An array class that knows its memory location. ++class CArray < Array ++ attr_reader :phys_start_addr ++ ++ def initialize(phys_start_addr, size, &block) ++ @phys_start_addr = phys_start_addr ++ ++ super(size, &block) ++ end ++ ++ def size_in_byte ++ inject(0) { |sum, n| sum + n.size_in_byte } ++ end ++end ++ ++#--------------------------------------------------------------------------------------------------- ++# Arch:: ++#--------------------------------------------------------------------------------------------------- ++module Arch ++#--------------------------------------------------------------------------------------------------- ++# Arch::ARMv8 ++#--------------------------------------------------------------------------------------------------- ++module ARMv8 ++# ARMv8 Table Descriptor. ++class Stage1TableDescriptor < BitField ++ module NextLevelTableAddr ++ OFFSET = 16 ++ NUMBITS = 32 ++ end ++ ++ module Type ++ OFFSET = 1 ++ NUMBITS = 1 ++ ++ BLOCK = 0 ++ TABLE = 1 ++ end ++ ++ module Valid ++ OFFSET = 0 ++ NUMBITS = 1 ++ ++ FALSE = 0 ++ TRUE = 1 ++ end ++ ++ attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) ++ attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) ++ attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) ++ ++ def next_level_table_addr=(addr) ++ addr >>= Granule64KiB::SHIFT ++ ++ self.__next_level_table_addr = addr ++ end ++ ++ private :__next_level_table_addr= ++end ++ ++# ARMv8 level 3 page descriptor. ++class Stage1PageDescriptor < BitField ++ module UXN ++ OFFSET = 54 ++ NUMBITS = 1 ++ ++ FALSE = 0 ++ TRUE = 1 ++ end ++ ++ module PXN ++ OFFSET = 53 ++ NUMBITS = 1 ++ ++ FALSE = 0 ++ TRUE = 1 ++ end ++ ++ module OutputAddr ++ OFFSET = 16 ++ NUMBITS = 32 ++ end ++ ++ module AF ++ OFFSET = 10 ++ NUMBITS = 1 ++ ++ FALSE = 0 ++ TRUE = 1 ++ end ++ ++ module SH ++ OFFSET = 8 ++ NUMBITS = 2 ++ ++ INNER_SHAREABLE = 0b11 ++ end ++ ++ module AP ++ OFFSET = 6 ++ NUMBITS = 2 ++ ++ RW_EL1 = 0b00 ++ RO_EL1 = 0b10 ++ end ++ ++ module AttrIndx ++ OFFSET = 2 ++ NUMBITS = 3 ++ end ++ ++ module Type ++ OFFSET = 1 ++ NUMBITS = 1 ++ ++ RESERVED_INVALID = 0 ++ PAGE = 1 ++ end ++ ++ module Valid ++ OFFSET = 0 ++ NUMBITS = 1 ++ ++ FALSE = 0 ++ TRUE = 1 ++ end ++ ++ attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) ++ attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) ++ attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) ++ attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) ++ attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) ++ attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) ++ attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) ++ attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) ++ attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) ++ ++ def output_addr=(addr) ++ addr >>= Granule64KiB::SHIFT ++ ++ self.__output_addr = addr ++ end ++ ++ private :__output_addr= ++end ++ ++# Translation table representing the structure defined in translation_table.rs. ++class TranslationTable ++ module MAIR ++ NORMAL = 1 ++ end ++ ++ def initialize ++ do_sanity_checks ++ ++ num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT ++ ++ @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) ++ ++ @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte ++ @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) ++ ++ populate_lvl2_entries ++ end ++ ++ def map_at(virt_region, phys_region, attributes) ++ return if virt_region.empty? ++ ++ raise if virt_region.size != phys_region.size ++ raise if phys_region.last > BSP.phys_addr_space_end_page ++ ++ virt_region.zip(phys_region).each do |virt_page, phys_page| ++ desc = page_descriptor_from(virt_page) ++ set_lvl3_entry(desc, phys_page, attributes) ++ end ++ end ++ ++ def to_binary ++ data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) ++ data.pack('Q<*') # "Q" == uint64_t, "<" == little endian ++ end ++ ++ def phys_tables_base_addr_binary ++ [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian ++ end ++ ++ def phys_tables_base_addr ++ @lvl2_phys_start_addr ++ end ++ ++ private ++ ++ def do_sanity_checks ++ raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE ++ raise unless (BSP.kernel_virt_addr_space_size modulo Granule512MiB::SIZE).zero? ++ end ++ ++ def new_lvl3(num_lvl2_tables, start_addr) ++ CArray.new(start_addr, num_lvl2_tables) do ++ temp = CArray.new(start_addr, 8192) do ++ Stage1PageDescriptor.new ++ end ++ start_addr += temp.size_in_byte ++ ++ temp ++ end ++ end ++ ++ def new_lvl2(num_lvl2_tables, start_addr) ++ CArray.new(start_addr, num_lvl2_tables) do ++ Stage1TableDescriptor.new ++ end ++ end ++ ++ def populate_lvl2_entries ++ @lvl2.each_with_index do |descriptor, i| ++ descriptor.next_level_table_addr = @lvl3[i].phys_start_addr ++ descriptor.type = Stage1TableDescriptor::Type::TABLE ++ descriptor.valid = Stage1TableDescriptor::Valid::TRUE ++ end ++ end ++ ++ def lvl2_lvl3_index_from(addr) ++ lvl2_index = addr >> Granule512MiB::SHIFT ++ lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT ++ ++ raise unless lvl2_index < @lvl2.size ++ ++ [lvl2_index, lvl3_index] ++ end ++ ++ def page_descriptor_from(virt_addr) ++ lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) ++ ++ @lvl3[lvl2_index][lvl3_index] ++ end ++ ++ # rubocop:disable Metrics/MethodLength ++ def set_attributes(desc, attributes) ++ case attributes.mem_attributes ++ when :CacheableDRAM ++ desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE ++ desc.attr_indx = MAIR::NORMAL ++ else ++ raise 'Invalid input' ++ end ++ ++ desc.ap = case attributes.acc_perms ++ when :ReadOnly ++ Stage1PageDescriptor::AP::RO_EL1 ++ when :ReadWrite ++ Stage1PageDescriptor::AP::RW_EL1 ++ else ++ raise 'Invalid input' ++ ++ end ++ ++ desc.pxn = if attributes.execute_never ++ Stage1PageDescriptor::PXN::TRUE ++ else ++ Stage1PageDescriptor::PXN::FALSE ++ end ++ ++ desc.uxn = Stage1PageDescriptor::UXN::TRUE ++ end ++ # rubocop:enable Metrics/MethodLength ++ ++ def set_lvl3_entry(desc, output_addr, attributes) ++ desc.output_addr = output_addr ++ desc.af = Stage1PageDescriptor::AF::TRUE ++ desc.type = Stage1PageDescriptor::Type::PAGE ++ desc.valid = Stage1PageDescriptor::Valid::TRUE ++ ++ set_attributes(desc, attributes) ++ end ++end ++end ++end + +diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/bsp.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb +--- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/bsp.rb ++++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb +@@ -0,0 +1,49 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2021-2023 Andre Richter ++ ++# Raspberry Pi 3 + 4 ++class RaspberryPi ++ attr_reader :kernel_granule, :kernel_virt_addr_space_size ++ ++ MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") ++ ++ def initialize ++ @kernel_granule = Granule64KiB ++ ++ @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') ++ ++ @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') ++ @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( ++ 'PHYS_KERNEL_TABLES_BASE_ADDR' ++ ) ++ end ++ ++ def phys_addr_of_kernel_tables ++ KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) ++ end ++ ++ def kernel_tables_offset_in_file ++ KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) ++ end ++ ++ def phys_kernel_tables_base_addr_offset_in_file ++ KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) ++ end ++ ++ def phys_addr_space_end_page ++ x = MEMORY_SRC.grep(/pub const END/) ++ x = case BSP_TYPE ++ when :rpi3 ++ x[0] ++ when :rpi4 ++ x[1] ++ else ++ raise ++ end ++ ++ x.scan(/\d+/).join.to_i(16) ++ end ++end + +diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/generic.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb +--- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/generic.rb ++++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb +@@ -0,0 +1,179 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2021-2023 Andre Richter ++ ++module Granule64KiB ++ SIZE = 64 * 1024 ++ SHIFT = Math.log2(SIZE).to_i ++end ++ ++module Granule512MiB ++ SIZE = 512 * 1024 * 1024 ++ SHIFT = Math.log2(SIZE).to_i ++ MASK = SIZE - 1 ++end ++ ++# Monkey-patch Integer with some helper functions. ++class Integer ++ def power_of_two? ++ self[0].zero? ++ end ++ ++ def aligned?(alignment) ++ raise unless alignment.power_of_two? ++ ++ (self & (alignment - 1)).zero? ++ end ++ ++ def align_up(alignment) ++ raise unless alignment.power_of_two? ++ ++ (self + alignment - 1) & ~(alignment - 1) ++ end ++ ++ def to_hex_underscore(with_leading_zeros: false) ++ fmt = with_leading_zeros ? 'modulo016x' : 'modulox' ++ value = format(fmt, self).to_s.reverse.scan(/.{4}|.+/).join('_').reverse ++ ++ format('0xmodulos', value) ++ end ++end ++ ++# An array where each value is the start address of a Page. ++class MemoryRegion < Array ++ def initialize(start_addr, size, granule_size) ++ raise unless start_addr.aligned?(granule_size) ++ raise unless size.positive? ++ raise unless (size modulo granule_size).zero? ++ ++ num_pages = size / granule_size ++ super(num_pages) do |i| ++ (i * granule_size) + start_addr ++ end ++ end ++end ++ ++# Collection of memory attributes. ++class AttributeFields ++ attr_reader :mem_attributes, :acc_perms, :execute_never ++ ++ def initialize(mem_attributes, acc_perms, execute_never) ++ @mem_attributes = mem_attributes ++ @acc_perms = acc_perms ++ @execute_never = execute_never ++ end ++ ++ def to_s ++ x = case @mem_attributes ++ when :CacheableDRAM ++ 'C' ++ else ++ '?' ++ end ++ ++ y = case @acc_perms ++ when :ReadWrite ++ 'RW' ++ when :ReadOnly ++ 'RO' ++ else ++ '??' ++ end ++ ++ z = @execute_never ? 'XN' : 'X ' ++ ++ "#{x} #{y} #{z}" ++ end ++end ++ ++# A container that describes a virt-to-phys region mapping. ++class MappingDescriptor ++ @max_section_name_length = 'Sections'.length ++ ++ class << self ++ attr_accessor :max_section_name_length ++ ++ def update_max_section_name_length(length) ++ @max_section_name_length = [@max_section_name_length, length].max ++ end ++ end ++ ++ attr_reader :name, :virt_region, :phys_region, :attributes ++ ++ def initialize(name, virt_region, phys_region, attributes) ++ @name = name ++ @virt_region = virt_region ++ @phys_region = phys_region ++ @attributes = attributes ++ end ++ ++ def to_s ++ name = @name.ljust(self.class.max_section_name_length) ++ virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) ++ phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) ++ size = ((@virt_region.size * 65_536) / 1024).to_s.rjust(3) ++ ++ "#{name} | #{virt_start} | #{phys_start} | #{size} KiB | #{@attributes}" ++ end ++ ++ def self.print_divider ++ print ' ' ++ print '-' * max_section_name_length ++ puts '--------------------------------------------------------------------' ++ end ++ ++ def self.print_header ++ print_divider ++ print ' ' ++ print 'Sections'.center(max_section_name_length) ++ print ' ' ++ print 'Virt Start Addr'.center(21) ++ print ' ' ++ print 'Phys Start Addr'.center(21) ++ print ' ' ++ print 'Size'.center(7) ++ print ' ' ++ print 'Attr'.center(7) ++ puts ++ print_divider ++ end ++end ++ ++def kernel_map_binary ++ mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors ++ ++ # Generate_mapping_descriptors updates the header being printed with this call. So it must come ++ # afterwards. ++ MappingDescriptor.print_header ++ ++ mapping_descriptors.each do |i| ++ print 'Generating'.rjust(12).green.bold ++ print ' ' ++ puts i ++ ++ TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) ++ end ++ ++ MappingDescriptor.print_divider ++end ++ ++def kernel_patch_tables(kernel_elf_path) ++ print 'Patching'.rjust(12).green.bold ++ print ' Kernel table struct at ELF file offset ' ++ puts BSP.kernel_tables_offset_in_file.to_hex_underscore ++ ++ File.binwrite(kernel_elf_path, TRANSLATION_TABLES.to_binary, BSP.kernel_tables_offset_in_file) ++end ++ ++def kernel_patch_base_addr(kernel_elf_path) ++ print 'Patching'.rjust(12).green.bold ++ print ' Kernel tables physical base address start argument to value ' ++ print TRANSLATION_TABLES.phys_tables_base_addr.to_hex_underscore ++ print ' at ELF file offset ' ++ puts BSP.phys_kernel_tables_base_addr_offset_in_file.to_hex_underscore ++ ++ File.binwrite(kernel_elf_path, TRANSLATION_TABLES.phys_tables_base_addr_binary, ++ BSP.phys_kernel_tables_base_addr_offset_in_file) ++end + +diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/kernel_elf.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb +--- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/kernel_elf.rb ++++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb +@@ -0,0 +1,96 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2021-2023 Andre Richter ++ ++# KernelELF ++class KernelELF ++ SECTION_FLAG_ALLOC = 2 ++ ++ def initialize(kernel_elf_path) ++ @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) ++ @symtab_section = @elf.section_by_name('.symtab') ++ end ++ ++ def machine ++ @elf.machine.to_sym ++ end ++ ++ def symbol_value(symbol_name) ++ @symtab_section.symbol_by_name(symbol_name).header.st_value ++ end ++ ++ def segment_containing_virt_addr(virt_addr) ++ @elf.each_segments do |segment| ++ return segment if segment.vma_in?(virt_addr) ++ end ++ end ++ ++ def virt_to_phys(virt_addr) ++ segment = segment_containing_virt_addr(virt_addr) ++ translation_offset = segment.header.p_vaddr - segment.header.p_paddr ++ ++ virt_addr - translation_offset ++ end ++ ++ def virt_addr_to_file_offset(virt_addr) ++ segment = segment_containing_virt_addr(virt_addr) ++ segment.vma_to_offset(virt_addr) ++ end ++ ++ def sections_in_segment(segment) ++ head = segment.mem_head ++ tail = segment.mem_tail ++ ++ sections = @elf.each_sections.select do |section| ++ file_offset = section.header.sh_addr ++ flags = section.header.sh_flags ++ ++ file_offset >= head && file_offset < tail && (flags & SECTION_FLAG_ALLOC != 0) ++ end ++ ++ sections.map(&:name).join(' ') ++ end ++ ++ def select_load_segments ++ @elf.each_segments.select do |segment| ++ segment.instance_of?(ELFTools::Segments::LoadSegment) ++ end ++ end ++ ++ def segment_get_acc_perms(segment) ++ if segment.readable? && segment.writable? ++ :ReadWrite ++ elsif segment.readable? ++ :ReadOnly ++ else ++ :Invalid ++ end ++ end ++ ++ def update_max_section_name_length(descriptors) ++ MappingDescriptor.update_max_section_name_length(descriptors.map { |i| i.name.size }.max) ++ end ++ ++ def generate_mapping_descriptors ++ descriptors = select_load_segments.map do |segment| ++ # Assume each segment is page aligned. ++ size = segment.mem_size.align_up(BSP.kernel_granule::SIZE) ++ virt_start_addr = segment.header.p_vaddr ++ phys_start_addr = segment.header.p_paddr ++ acc_perms = segment_get_acc_perms(segment) ++ execute_never = !segment.executable? ++ section_names = sections_in_segment(segment) ++ ++ virt_region = MemoryRegion.new(virt_start_addr, size, BSP.kernel_granule::SIZE) ++ phys_region = MemoryRegion.new(phys_start_addr, size, BSP.kernel_granule::SIZE) ++ attributes = AttributeFields.new(:CacheableDRAM, acc_perms, execute_never) ++ ++ MappingDescriptor.new(section_names, virt_region, phys_region, attributes) ++ end ++ ++ update_max_section_name_length(descriptors) ++ descriptors ++ end ++end + +diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/main.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb +--- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/main.rb ++++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb +@@ -0,0 +1,46 @@ ++#!/usr/bin/env ruby ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2021-2023 Andre Richter ++ ++require 'rubygems' ++require 'bundler/setup' ++require 'colorize' ++require 'elftools' ++ ++require_relative 'generic' ++require_relative 'kernel_elf' ++require_relative 'bsp' ++require_relative 'arch' ++ ++BSP_TYPE = ARGV[0].to_sym ++kernel_elf_path = ARGV[1] ++ ++start = Time.now ++ ++KERNEL_ELF = KernelELF.new(kernel_elf_path) ++ ++BSP = case BSP_TYPE ++ when :rpi3, :rpi4 ++ RaspberryPi.new ++ else ++ raise ++ end ++ ++TRANSLATION_TABLES = case KERNEL_ELF.machine ++ when :AArch64 ++ Arch::ARMv8::TranslationTable.new ++ else ++ raise ++ end ++ ++kernel_map_binary ++kernel_patch_tables(kernel_elf_path) ++kernel_patch_base_addr(kernel_elf_path) ++ ++elapsed = Time.now - start ++ ++print 'Finished'.rjust(12).green.bold ++puts " in #{elapsed.round(2)}s" + +``` diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml b/15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml new file mode 100644 index 000000000..a0652b4f3 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml @@ -0,0 +1,57 @@ +[package] +name = "mingo" +version = "0.15.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##------------------------------------------------------------------------------------------------- +## Dependencies +##------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##------------------------------------------------------------------------------------------------- +## Testing +##------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/build.rs b/15_virtual_mem_part3_precomputed_tables/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..b76176df5 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use crate::{memory, memory::Address}; +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(crate::kernel_init as *const () as u64); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, + phys_boot_core_stack_end_exclusive_addr: u64, +) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..48c3f8a70 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Load the base address of the kernel's translation tables. + ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. + ADR_REL x1, __boot_core_stack_end_exclusive + mov sp, x1 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x2, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x3, CNTFRQ_EL0 + cmp x3, xzr + b.eq .L_parking_loop + str w3, [x2] + + // Jump to Rust code. x0 and x1 hold the function arguments provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/smp.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/smp.rs new file mode 100644 index 000000000..491920389 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..730198009 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use crate::exception; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!(include_str!("exception.s")); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.s b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..91805ee7c --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 17 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception/asynchronous.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..811ef138e --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..e0717a7f5 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::{mmu::TranslationGranule, Address, Physical}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + fn configure_translation_control(&self) { + let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI0::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG0::KiB_64 + + TCR_EL1::SH0::Inner + + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD0::EnableTTBR0Walks + + TCR_EL1::A1::TTBR0 + + TCR_EL1::T0SZ.val(t0sz) + + TCR_EL1::EPD1::DisableTTBR1Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Set the "Translation Table Base Register". + TTBR0_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..8cba4cd7c --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,506 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, + memory::{ + self, + mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, + }, + Address, Physical, Virtual, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn virt_start_addr(&self) -> Address; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], + + /// Have the tables been initialized? + initialized: bool, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl StartAddr for [T; N] { + fn virt_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +/// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. +impl convert::TryFrom> for AttributeFields { + type Error = &'static str; + + fn try_from( + desc: InMemoryRegister, + ) -> Result { + let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { + memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, + memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, + _ => return Err("Unexpected memory attribute"), + }; + + let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, + _ => return Err("Unexpected access permission"), + }; + + let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; + + Ok(AttributeFields { + mem_attributes, + acc_perms, + execute_never, + }) + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_page_addr( + phys_output_page_addr: PageAddress, + attribute_fields: &AttributeFields, + ) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } + + /// Returns the valid bit. + fn is_valid(&self) -> bool { + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } + + /// Returns the output page. + fn output_page_addr(&self) -> PageAddress { + let shifted = InMemoryRegister::::new(self.value) + .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; + + PageAddress::from(shifted << Granule64KiB::SHIFT) + } + + /// Returns the attributes. + fn try_attributes(&self) -> Result { + InMemoryRegister::::new(self.value).try_into() + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }>; +} + +impl FixedSizeTranslationTable { + /// Create an instance. + #[allow(clippy::assertions_on_constants)] + const fn _new(for_precompute: bool) -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + initialized: for_precompute, + } + } + + pub const fn new_for_precompute() -> Self { + Self::_new(true) + } + + #[cfg(test)] + pub fn new_for_runtime() -> Self { + Self::_new(false) + } + + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { + let addr = virt_page_addr.into_inner().as_usize(); + let lvl2_index = addr >> Granule512MiB::SHIFT; + let lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); + } + + Ok((lvl2_index, lvl3_index)) + } + + /// Returns the PageDescriptor corresponding to the supplied page address. + #[inline(always)] + fn page_descriptor_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<&PageDescriptor, &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &self.lvl3[lvl2_index][lvl3_index]; + + Ok(desc) + } + + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. + #[inline(always)] + fn set_page_descriptor_from_page_addr( + &mut self, + virt_page_addr: PageAddress, + new_desc: &PageDescriptor, + ) -> Result<(), &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &mut self.lvl3[lvl2_index][lvl3_index]; + + if desc.is_valid() { + return Err("Virtual page is already mapped"); + } + + *desc = *new_desc; + Ok(()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable +{ + fn init(&mut self) -> Result<(), &'static str> { + if self.initialized { + return Ok(()); + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { + let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); + let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; + + Ok(()) + } + + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + assert!(self.initialized, "Translation tables not initialized"); + + if virt_region.size() != phys_region.size() { + return Err("Tried to map memory regions with unequal sizes"); + } + + if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() + { + return Err("Tried to map outside of physical address space"); + } + + let iter = phys_region.into_iter().zip(virt_region.into_iter()); + for (phys_page_addr, virt_page_addr) in iter { + let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); + let virt_page = virt_page_addr; + + self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; + } + + Ok(()) + } + + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str> { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + Ok(page_desc.output_page_addr()) + } + + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + page_desc.try_attributes() + } + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str> { + let virt_page = PageAddress::from(virt_addr.align_down_page()); + let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; + + Ok(phys_page.into_inner() + virt_addr.offset_into_page()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1>; + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/time.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..2dfaec8d6 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(feature = "bsp_rpi4")] +mod arm; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm.rs new file mode 100644 index 000000000..8d1cbfbd8 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2.rs new file mode 100644 index 000000000..256de7041 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new( + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, + ) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs new file mode 100644 index 000000000..0fd16bb38 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs new file mode 100644 index 000000000..1fc9d70e9 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, + state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num % 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..7b7c288b7 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..812156f44 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs new file mode 100644 index 000000000..62f078002 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.periph.print_handler(); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs new file mode 100644 index 000000000..a26bff8d0 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), + } + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() % 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..b424d4be7 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/common.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..3ce1d8d81 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use crate::memory::{Address, Virtual}; +use core::{fmt, marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: Address, + phantom: PhantomData T>, +} + +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: Address) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr.as_usize() as *const _) } + } +} + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..30421dfa6 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/cpu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/driver.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..a1f55b170 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, + memory, + memory::mmu::MMIODescriptor, +}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering}, +}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi3")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi4")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the UART driver. +unsafe fn post_init_uart() -> Result<(), &'static str> { + console::register_console(PL011_UART.assume_init_ref()); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_gpio() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; + + GPIO.write(device_driver::GPIO::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +unsafe fn post_init_gpio() -> Result<(), &'static str> { + GPIO.assume_init_ref().map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi3")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &periph_mmio_descriptor, + )?; + + INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi4")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); + let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; + + let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); + let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; + + INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the interrupt controller driver. +unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_gpio() -> Result<(), &'static str> { + instantiate_gpio()?; + + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( + GPIO.assume_init_ref(), + Some(post_init_gpio), + None, + ); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { + instantiate_interrupt_controller()?; + + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + INTERRUPT_CONTROLLER.assume_init_ref(), + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + use crate::cpu; + + unsafe { + instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); + console::register_console(PL011_UART.assume_init_ref()); + }; +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception.rs new file mode 100644 index 000000000..a9eaa6ac4 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception/asynchronous.rs new file mode 100644 index 000000000..776182fd0 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +#[cfg(feature = "bsp_rpi3")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; + + pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +#[cfg(feature = "bsp_rpi4")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::IRQNumber; + + pub const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..63393bae5 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,103 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +INCLUDE kernel_virt_addr_space_size.ld; + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + __data_start = .; + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld new file mode 100644 index 000000000..c5d58c30a --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld @@ -0,0 +1 @@ +__kernel_virt_addr_space_size = 1024 * 1024 * 1024 diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..0d963aa30 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | data_end_exclusive +//! | | +//! +//! +//! +//! +//! +//! The virtual memory layout is as follows: +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_start == data_end_exclusive +//! | VA region for MMIO remapping | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_end_exclusive +//! | | +pub mod mmu; + +use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; + + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + + static __boot_core_stack_start: UnsafeCell<()>; + static __boot_core_stack_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + use super::*; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); + pub const PERIPHERAL_IC_SIZE: usize = 0x24; + + pub const GPIO_START: Address = Address::new(0x3F20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const END: Address = Address::new(0x4001_0000); + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const GPIO_START: Address = Address::new(0xFE20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0xFE20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const GICD_START: Address = Address::new(0xFF84_1000); + pub const GICD_SIZE: usize = 0x824; + + pub const GICC_START: Address = Address::new(0xFF84_2000); + pub const GICC_SIZE: usize = 0x14; + + pub const END: Address = Address::new(0xFF85_0000); + } + + pub const END: Address = mmio::END; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_code_start() -> PageAddress { + PageAddress::from(unsafe { __code_start.get() as usize }) +} + +/// Size of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_size() -> usize { + unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } +} + +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { + PageAddress::from(unsafe { __data_start.get() as usize }) +} + +/// Size of the data segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn data_size() -> usize { + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } +} + +/// Start page address of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_mmio_remap_start() -> PageAddress { + PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) +} + +/// Size of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn mmio_remap_size() -> usize { + unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } +} + +/// Start page address of the boot core's stack. +#[inline(always)] +fn virt_boot_core_stack_start() -> PageAddress { + PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) +} + +/// Size of the boot core's stack. +#[inline(always)] +fn boot_core_stack_size() -> usize { + unsafe { + (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Exclusive end address of the physical address space. +#[inline(always)] +pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { + PageAddress::from(map::END) +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..ce3d67506 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use crate::{ + memory::{ + mmu::{ + self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, + MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type KernelTranslationTable = + ::TableStartFromBottom; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to +/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. +pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + +/// The kernel's virtual address space defined by this BSP. +pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// It is mandatory that InitStateLock is transparent. +/// +/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. +/// There is a unit tests that checks this porperty. +#[link_section = ".data"] +#[no_mangle] +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new_for_precompute()); + +/// This value is needed during early boot for MMU setup. +/// +/// This will be patched to the correct value by the "translation table tool" after linking. This +/// given value here is just a dummy. +#[link_section = ".text._start_arguments"] +#[no_mangle] +static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This is a hack for retrieving the value for the kernel's virtual address space size as a +/// constant from a common place, since it is needed as a compile-time/link-time constant in both, +/// the linker script and the Rust sources. +#[allow(clippy::needless_late_init)] +const fn kernel_virt_addr_space_size() -> usize { + let __kernel_virt_addr_space_size; + + include!("../kernel_virt_addr_space_size.ld"); + + __kernel_virt_addr_space_size +} + +/// Helper function for calculating the number of pages the given parameter spans. +const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); + assert!(size % KernelGranule::SIZE == 0); + + size >> KernelGranule::SHIFT +} + +/// The code pages of the kernel binary. +fn virt_code_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::code_size()); + + let start_page_addr = super::virt_code_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The data pages of the kernel binary. +fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); + + let start_page_addr = super::virt_data_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The boot core stack pages. +fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); + + let start_page_addr = super::virt_boot_core_stack_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +// There is no reason to expect the following conversions to fail, since they were generated offline +// by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. +fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { + let phys_start_page_addr = + generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) + .unwrap(); + + let phys_end_exclusive_page_addr = phys_start_page_addr + .checked_offset(virt_region.num_pages() as isize) + .unwrap(); + + MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) +} + +fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { + generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} + +/// The MMIO remap pages. +pub fn virt_mmio_remap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::mmio_remap_size()); + + let start_page_addr = super::virt_mmio_remap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Add mapping records for the kernel binary. +/// +/// The actual translation table entries for the kernel binary are generated using the offline +/// `translation table tool` and patched into the kernel binary. This function just adds the mapping +/// record entries. +pub fn kernel_add_mapping_records_for_precomputed() { + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", + &virt_boot_core_stack_region, + &kernel_virt_to_phys_region(virt_boot_core_stack_region), + &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), + ); + + let virt_code_region = virt_code_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel code and RO data", + &virt_code_region, + &kernel_virt_to_phys_region(virt_code_region), + &kernel_page_attributes(virt_code_region.start_page_addr()), + ); + + let virt_data_region = virt_data_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel data and bss", + &virt_data_region, + &kernel_virt_to_phys_region(virt_data_region), + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/common.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/common.rs new file mode 100644 index 000000000..2ad7e4c1e --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/common.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Check if a value is aligned to a given size. +#[inline(always)] +pub const fn is_aligned(value: usize, alignment: usize) -> bool { + assert!(alignment.is_power_of_two()); + + (value & (alignment - 1)) == 0 +} + +/// Align down. +#[inline(always)] +pub const fn align_down(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + value & !(alignment - 1) +} + +/// Align up. +#[inline(always)] +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + (value + alignment - 1) & !(alignment - 1) +} + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/console.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/console.rs new file mode 100644 index 000000000..f03634649 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.read(|con| *con) +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/console/null_console.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu.rs new file mode 100644 index 000000000..8716a918b --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +pub mod smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/boot.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/smp.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/smp.rs new file mode 100644 index 000000000..de612d589 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/driver.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/driver.rs new file mode 100644 index 000000000..2edf8b854 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/driver.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner +where + T: 'static, +{ + next_index: usize, + descriptors: [Option>; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager +where + T: 'static, +{ + inner: InitStateLock>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner +where + T: 'static + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + irq_number, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager +where + T: fmt::Display + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: InitStateLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.write(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.read(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + self.for_each_descriptor(|descriptor| { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/exception.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..2c874dd60 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous/null_irq_manager.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous/null_irq_manager.rs new file mode 100644 index 000000000..38919ffe4 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs new file mode 100644 index 000000000..71350bd09 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(generic_const_exprs)] +#![feature(int_roundings)] +#![feature(is_sorted)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(step_trait)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +mod panic_wait; +mod synchronization; + +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod state; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +#[cfg(not(test))] +extern "Rust" { + fn kernel_init() -> !; +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/main.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/main.rs new file mode 100644 index 000000000..e41cfaa0d --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/main.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + +/// Early init code. +/// +/// When this code runs, virtual memory is already enabled. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - Printing will not work until the respective driver's MMIO is remapped. +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + + bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online:"); + memory::mmu::kernel_print_mappings(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + + info!("Echoing input now"); + cpu::wait_forever(); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs new file mode 100644 index 000000000..6131bdb6c --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; + +use crate::{bsp, common}; +use core::{ + fmt, + marker::PhantomData, + ops::{Add, Sub}, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Physical {} + +/// Zero-sized type to mark a virtual address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl AddressType for Physical {} +impl AddressType for Virtual {} + +impl Address { + /// Create an instance. + pub const fn new(value: usize) -> Self { + Self { + value, + _address_type: PhantomData, + } + } + + /// Convert to usize. + pub const fn as_usize(self) -> usize { + self.value + } + + /// Align down to page size. + #[must_use] + pub const fn align_down_page(self) -> Self { + let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Align up to page size. + #[must_use] + pub const fn align_up_page(self) -> Self { + let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Checks if the address is page aligned. + pub const fn is_page_aligned(&self) -> bool { + common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) + } + + /// Return the address' offset into the corresponding page. + pub const fn offset_into_page(&self) -> usize { + self.value & bsp::memory::mmu::KernelGranule::MASK + } +} + +impl Add for Address { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: usize) -> Self::Output { + match self.value.checked_add(rhs) { + None => panic!("Overflow on Address::add"), + Some(x) => Self::new(x), + } + } +} + +impl Sub> for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Address) -> Self::Output { + match self.value.checked_sub(rhs.value) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q3: u8 = ((self.value >> 32) & 0xff) as u8; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:02x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q4: u16 = ((self.value >> 48) & 0xffff) as u16; + let q3: u16 = ((self.value >> 32) & 0xffff) as u16; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:04x}_", q4)?; + write!(f, "{:04x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of [Address] methods. + #[kernel_test] + fn address_type_method_sanity() { + let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); + + assert_eq!( + addr.align_down_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE + ); + + assert_eq!( + addr.align_up_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + + assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..f19758c19 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod mapping_record; +mod page_alloc; +mod translation_table; +mod types; + +use crate::{ + bsp, + memory::{Address, Physical, Virtual}, + synchronization::{self, interface::Mutex}, + warn, +}; +use core::{fmt, num::NonZeroUsize}; + +pub use types::*; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Turns on the MMU for the first time and enables data and instruction caching. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +use interface::MMU; +use synchronization::interface::ReadWriteEx; +use translation_table::interface::TranslationTable; + +/// Map a region in the kernel's translation tables. +/// +/// No input checks done, input is passed through to the architectural implementation. +/// +/// # Safety +/// +/// - See `map_at()`. +/// - Does not prevent aliasing. +unsafe fn kernel_map_at_unchecked( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + + kernel_add_mapping_record(name, virt_region, phys_region, attr); + + Ok(()) +} + +/// Try to translate a kernel virtual address to a physical address. +/// +/// Will only succeed if there exists a valid mapping for the input address. +fn try_kernel_virt_addr_to_phys_addr( + virt_addr: Address, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's mask. + pub const MASK: usize = Self::SIZE - 1; + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +pub fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Add an entry to the mapping info record. +pub fn kernel_add_mapping_record( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) { + if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { + warn!("{}", x); + } +} + +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +/// +/// # Safety +/// +/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + let phys_region = MemoryRegion::from(*mmio_descriptor); + let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); + + // Check if an identical region has been mapped for another driver. If so, reuse it. + let virt_addr = if let Some(addr) = + mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) + { + addr + // Otherwise, allocate a new region and map it. + } else { + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, + }; + + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + virt_region.start_addr() + }; + + Ok(virt_addr + offset_into_start_page) +} + +/// Try to translate a kernel virtual page address to a physical page address. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_virt_page_addr_to_phys_page_addr( + virt_page_addr: PageAddress, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) +} + +/// Try to get the attributes of a kernel page. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_page_attributes( + virt_page_addr: PageAddress, +) -> Result { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_page_attributes(virt_page_addr)) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() +} + +/// Enable the MMU and data + instruction caching. +/// +/// # Safety +/// +/// - Crucial function during kernel init. Changes the the complete memory view of the processor. +#[inline(always)] +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/mapping_record.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/mapping_record.rs new file mode 100644 index 000000000..0e0792201 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/mapping_record.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + +use super::{ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Type describing a virtual memory mapping. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +struct MappingRecordEntry { + pub users: [Option<&'static str>; 5], + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, + pub attribute_fields: AttributeFields, +} + +struct MappingRecord { + inner: [Option; 12], +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MAPPING_RECORD: InitStateLock = + InitStateLock::new(MappingRecord::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl MappingRecordEntry { + pub fn new( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Self { + Self { + users: [Some(name), None, None, None, None], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), + attribute_fields: *attr, + } + } + + fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { + if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { + return Ok(x); + }; + + Err("Storage for user info exhausted") + } + + pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { + let x = self.find_next_free_user()?; + *x = Some(user); + Ok(()) + } +} + +impl MappingRecord { + pub const fn new() -> Self { + Self { inner: [None; 12] } + } + + fn size(&self) -> usize { + self.inner.iter().filter(|x| x.is_some()).count() + } + + fn sort(&mut self) { + let upper_bound_exclusive = self.size(); + let entries = &mut self.inner[0..upper_bound_exclusive]; + + if !entries.is_sorted_by_key(|item| item.unwrap().virt_start_addr) { + entries.sort_unstable_by_key(|item| item.unwrap().virt_start_addr) + } + } + + fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { + if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { + return Ok(x); + } + + Err("Storage for mapping info exhausted") + } + + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() + .filter_map(|x| x.as_mut()) + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { + return false; + } + + if x.num_pages != phys_region.num_pages() { + return false; + } + + true + }) + } + + pub fn add( + &mut self, + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + let x = self.find_next_free()?; + + *x = Some(MappingRecordEntry::new( + name, + virt_region, + phys_region, + attr, + )); + + self.sort(); + + Ok(()) + } + + pub fn print(&self) { + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", + "Virtual", "Physical", "Size", "Attr", "Entity" + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + + for i in self.inner.iter().flatten() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match i.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if i.attribute_fields.execute_never { + "XN" + } else { + "X" + }; + + info!( + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, + phys_end_inclusive, + size, + unit, + attr, + acc_p, + xn, + i.users[0].unwrap() + ); + + for k in i.users[1..].iter() { + if let Some(additional_user) = *k { + info!( + " | {}", + additional_user + ); + } + } + } + + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +/// Add an entry to the mapping info record. +pub fn kernel_add( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) +} + +pub fn kernel_find_and_insert_mmio_duplicate( + mmio_descriptor: &MMIODescriptor, + new_user: &'static str, +) -> Option> { + let phys_region: MemoryRegion = (*mmio_descriptor).into(); + + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + + if let Err(x) = dup.add_user(new_user) { + warn!("{}", x); + } + + Some(dup.virt_start_addr) + }) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print() { + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/page_alloc.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/page_alloc.rs new file mode 100644 index 000000000..344afd200 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/page_alloc.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Page allocation. + +use super::MemoryRegion; +use crate::{ + memory::{AddressType, Virtual}, + synchronization::IRQSafeNullLock, + warn, +}; +use core::num::NonZeroUsize; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A page allocator that can be lazyily initialized. +pub struct PageAllocator { + pool: Option>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = + IRQSafeNullLock::new(PageAllocator::new()); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's MMIO virtual address allocator. +pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { + &KERNEL_MMIO_VA_ALLOCATOR +} + +impl PageAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { pool: None } + } + + /// Initialize the allocator. + pub fn init(&mut self, pool: MemoryRegion) { + if self.pool.is_some() { + warn!("Already initialized"); + return; + } + + self.pool = Some(pool); + } + + /// Allocate a number of pages. + pub fn alloc( + &mut self, + num_requested_pages: NonZeroUsize, + ) -> Result, &'static str> { + if self.pool.is_none() { + return Err("Allocator not initialized"); + } + + self.pool + .as_mut() + .unwrap() + .take_first_n_pages(num_requested_pages) + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..41368daed --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +use super::{AttributeFields, MemoryRegion}; +use crate::memory::{Address, Physical, Virtual}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(target_arch = "aarch64")] +pub use arch_translation_table::FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Translation table interfaces. +pub mod interface { + use crate::memory::mmu::PageAddress; + + use super::*; + + /// Translation table operations. + pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self) -> Result<(), &'static str>; + + /// Map the given virtual memory region to the given physical memory region. + /// + /// # Safety + /// + /// - Using wrong attributes can cause multiple issues of different nature in the system. + /// - It is not required that the architectural implementation prevents aliasing. That is, + /// mapping to the same physical memory using multiple virtual addresses, which would + /// break Rust's ownership assumptions. This should be protected against in the kernel's + /// generic MMU code. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; + + /// Try to translate a virtual page address to a physical page address. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str>; + + /// Try to get the attributes of a page. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result; + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str>; + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use arch_translation_table::MinSizeTranslationTable; + use interface::TranslationTable; + use test_macros::kernel_test; + + /// Sanity checks for the TranslationTable implementation. + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. + let mut tables = MinSizeTranslationTable::new_for_runtime(); + + assert_eq!(tables.init(), Ok(())); + + let virt_start_page_addr: PageAddress = PageAddress::from(0); + let virt_end_exclusive_page_addr: PageAddress = + virt_start_page_addr.checked_offset(5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + + let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + + assert_eq!( + tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), + Ok(phys_start_page_addr) + ); + + assert_eq!( + tables.try_page_attributes(virt_start_page_addr.checked_offset(6).unwrap()), + Err("Page marked invalid") + ); + + assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); + + let virt_addr = virt_start_page_addr.into_inner() + 0x100; + let phys_addr = phys_start_page_addr.into_inner() + 0x100; + assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs new file mode 100644 index 000000000..8feee064b --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + +use crate::{ + bsp, common, + memory::{Address, AddressType, Physical}, +}; +use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct PageAddress { + inner: Address, +} + +/// A type that describes a region of memory in quantities of pages. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// An MMIO descriptor for use in device drivers. +#[derive(Copy, Clone)] +pub struct MMIODescriptor { + start_addr: Address, + end_addr_exclusive: Address, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------ +// PageAddress +//------------------------------------------------------------------------------ +impl PageAddress { + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + } + + /// Calculates the offset from the page address. + /// + /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * + /// page_size`. + pub fn checked_offset(self, count: isize) -> Option { + if count == 0 { + return Some(self); + } + + let delta = count + .unsigned_abs() + .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; + let result = if count.is_positive() { + self.inner.as_usize().checked_add(delta)? + } else { + self.inner.as_usize().checked_sub(delta)? + }; + + Some(Self { + inner: Address::new(result), + }) + } +} + +impl From for PageAddress { + fn from(addr: usize) -> Self { + assert!( + common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), + "Input usize not page aligned" + ); + + Self { + inner: Address::new(addr), + } + } +} + +impl From> for PageAddress { + fn from(addr: Address) -> Self { + assert!(addr.is_page_aligned(), "Input Address not page aligned"); + + Self { inner: addr } + } +} + +impl Step for PageAddress { + fn steps_between(start: &Self, end: &Self) -> Option { + if start > end { + return None; + } + + // Since start <= end, do unchecked arithmetic. + Some( + (end.inner.as_usize() - start.inner.as_usize()) + >> bsp::memory::mmu::KernelGranule::SHIFT, + ) + } + + fn forward_checked(start: Self, count: usize) -> Option { + start.checked_offset(count as isize) + } + + fn backward_checked(start: Self, count: usize) -> Option { + start.checked_offset(-(count as isize)) + } +} + +//------------------------------------------------------------------------------ +// MemoryRegion +//------------------------------------------------------------------------------ +impl MemoryRegion { + /// Create an instance. + pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { + assert!(start <= end_exclusive); + + Self { + start, + end_exclusive, + } + } + + fn as_range(&self) -> Range> { + self.into_iter() + } + + /// Returns the start page address. + pub fn start_page_addr(&self) -> PageAddress { + self.start + } + + /// Returns the start address. + pub fn start_addr(&self) -> Address { + self.start.into_inner() + } + + /// Returns the exclusive end page address. + pub fn end_exclusive_page_addr(&self) -> PageAddress { + self.end_exclusive + } + + /// Returns the exclusive end page address. + pub fn end_inclusive_page_addr(&self) -> PageAddress { + self.end_exclusive.checked_offset(-1).unwrap() + } + + /// Checks if self contains an address. + pub fn contains(&self, addr: Address) -> bool { + let page_addr = PageAddress::from(addr.align_down_page()); + self.as_range().contains(&page_addr) + } + + /// Checks if there is an overlap with another memory region. + pub fn overlaps(&self, other_region: &Self) -> bool { + let self_range = self.as_range(); + + self_range.contains(&other_region.start_page_addr()) + || self_range.contains(&other_region.end_inclusive_page_addr()) + } + + /// Returns the number of pages contained in this region. + pub fn num_pages(&self) -> usize { + PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() + } + + /// Returns the size in bytes of this region. + pub fn size(&self) -> usize { + // Invariant: start <= end_exclusive, so do unchecked arithmetic. + let end_exclusive = self.end_exclusive.into_inner().as_usize(); + let start = self.start.into_inner().as_usize(); + + end_exclusive - start + } + + /// Splits the MemoryRegion like: + /// + /// -------------------------------------------------------------------------------- + /// | | | | | | | | | | | | | | | | | | | + /// -------------------------------------------------------------------------------- + /// ^ ^ ^ + /// | | | + /// left_start left_end_exclusive | + /// | + /// ^ | + /// | | + /// right_start right_end_exclusive + /// + /// Left region is returned to the caller. Right region is the new region for this struct. + pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { + let count: usize = num_pages.into(); + + let left_end_exclusive = self.start.checked_offset(count as isize); + let left_end_exclusive = match left_end_exclusive { + None => return Err("Overflow while calculating left_end_exclusive"), + Some(x) => x, + }; + + if left_end_exclusive > self.end_exclusive { + return Err("Not enough free pages"); + } + + let allocation = Self { + start: self.start, + end_exclusive: left_end_exclusive, + }; + self.start = left_end_exclusive; + + Ok(allocation) + } +} + +impl IntoIterator for MemoryRegion { + type Item = PageAddress; + type IntoIter = Range; + + fn into_iter(self) -> Self::IntoIter { + Range { + start: self.start, + end: self.end_exclusive, + } + } +} + +impl From for MemoryRegion { + fn from(desc: MMIODescriptor) -> Self { + let start = PageAddress::from(desc.start_addr.align_down_page()); + let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); + + Self { + start, + end_exclusive, + } + } +} + +//------------------------------------------------------------------------------ +// MMIODescriptor +//------------------------------------------------------------------------------ + +impl MMIODescriptor { + /// Create an instance. + pub const fn new(start_addr: Address, size: usize) -> Self { + assert!(size > 0); + let end_addr_exclusive = Address::new(start_addr.as_usize() + size); + + Self { + start_addr, + end_addr_exclusive, + } + } + + /// Return the start address. + pub const fn start_addr(&self) -> Address { + self.start_addr + } + + /// Return the exclusive end address. + pub fn end_addr_exclusive(&self) -> Address { + self.end_addr_exclusive + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::Virtual; + use test_macros::kernel_test; + + /// Sanity of [PageAddress] methods. + #[kernel_test] + fn pageaddress_type_method_sanity() { + let page_addr: PageAddress = + PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); + + assert_eq!( + page_addr.checked_offset(-2), + Some(PageAddress::::from(0)) + ); + + assert_eq!( + page_addr.checked_offset(2), + Some(PageAddress::::from( + bsp::memory::mmu::KernelGranule::SIZE * 4 + )) + ); + + assert_eq!( + PageAddress::::from(0).checked_offset(0), + Some(PageAddress::::from(0)) + ); + assert_eq!(PageAddress::::from(0).checked_offset(-1), None); + + let max_page_addr = Address::::new(usize::MAX).align_down_page(); + assert_eq!( + PageAddress::::from(max_page_addr).checked_offset(1), + None + ); + + let zero = PageAddress::::from(0); + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); + } + + /// Sanity of [MemoryRegion] methods. + #[kernel_test] + fn memoryregion_type_method_sanity() { + let zero = PageAddress::::from(0); + let zero_region = MemoryRegion::new(zero, zero); + assert_eq!(zero_region.num_pages(), 0); + assert_eq!(zero_region.size(), 0); + + let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); + let one_region = MemoryRegion::new(zero, one); + assert_eq!(one_region.num_pages(), 1); + assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); + + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + let mut three_region = MemoryRegion::new(zero, three); + assert!(three_region.contains(zero.into_inner())); + assert!(!three_region.contains(three.into_inner())); + assert!(three_region.overlaps(&one_region)); + + let allocation = three_region + .take_first_n_pages(NonZeroUsize::new(2).unwrap()) + .unwrap(); + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + + for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE + ); + } + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/panic_wait.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/panic_wait.rs new file mode 100644 index 000000000..c6f3a9c7b --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/panic_wait.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, exception, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + _panic_exit() +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/print.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/state.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/state.rs new file mode 100644 index 000000000..6d99beedb --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/synchronization.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/synchronization.rs new file mode 100644 index 000000000..5740b63e5 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/synchronization.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use crate::{exception, state}; + +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/src/time.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rb b/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..682ea9b8a --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, memory, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..1581a02e0 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, memory, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..da64739c8 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + info!("Writing beyond mapped area to address 9 GiB..."); + let big_addr: u64 = 9 * 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rb b/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..1a3029112 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs new file mode 100644 index 000000000..fcace8979 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception, memory}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + memory::init(); + bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/boot_test_string.rb b/15_virtual_mem_part3_precomputed_tables/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_exit_success/mod.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_wait_forever/mod.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/Cargo.toml b/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/src/lib.rs b/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/15_virtual_mem_part3_precomputed_tables/libraries/test-types/Cargo.toml b/15_virtual_mem_part3_precomputed_tables/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/15_virtual_mem_part3_precomputed_tables/libraries/test-types/src/lib.rs b/15_virtual_mem_part3_precomputed_tables/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb new file mode 100644 index 000000000..d8b5d04a1 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb @@ -0,0 +1,312 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Bitfield manipulation. +class BitField + def initialize + @value = 0 + end + + def self.attr_bitfield(name, offset, num_bits) + define_method("#{name}=") do |bits| + mask = (2**num_bits) - 1 + + raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? + + # Clear bitfield + @value &= ~(mask << offset) + + # Set it + @value |= (bits << offset) + end + end + + def to_i + @value + end + + def size_in_byte + 8 + end +end + +# An array class that knows its memory location. +class CArray < Array + attr_reader :phys_start_addr + + def initialize(phys_start_addr, size, &block) + @phys_start_addr = phys_start_addr + + super(size, &block) + end + + def size_in_byte + inject(0) { |sum, n| sum + n.size_in_byte } + end +end + +#--------------------------------------------------------------------------------------------------- +# Arch:: +#--------------------------------------------------------------------------------------------------- +module Arch +#--------------------------------------------------------------------------------------------------- +# Arch::ARMv8 +#--------------------------------------------------------------------------------------------------- +module ARMv8 +# ARMv8 Table Descriptor. +class Stage1TableDescriptor < BitField + module NextLevelTableAddr + OFFSET = 16 + NUMBITS = 32 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + BLOCK = 0 + TABLE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def next_level_table_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__next_level_table_addr = addr + end + + private :__next_level_table_addr= +end + +# ARMv8 level 3 page descriptor. +class Stage1PageDescriptor < BitField + module UXN + OFFSET = 54 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module PXN + OFFSET = 53 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module OutputAddr + OFFSET = 16 + NUMBITS = 32 + end + + module AF + OFFSET = 10 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module SH + OFFSET = 8 + NUMBITS = 2 + + INNER_SHAREABLE = 0b11 + end + + module AP + OFFSET = 6 + NUMBITS = 2 + + RW_EL1 = 0b00 + RO_EL1 = 0b10 + end + + module AttrIndx + OFFSET = 2 + NUMBITS = 3 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + RESERVED_INVALID = 0 + PAGE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) + attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) + attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) + attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) + attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) + attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) + attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def output_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__output_addr = addr + end + + private :__output_addr= +end + +# Translation table representing the structure defined in translation_table.rs. +class TranslationTable + module MAIR + NORMAL = 1 + end + + def initialize + do_sanity_checks + + num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT + + @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) + + @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte + @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) + + populate_lvl2_entries + end + + def map_at(virt_region, phys_region, attributes) + return if virt_region.empty? + + raise if virt_region.size != phys_region.size + raise if phys_region.last > BSP.phys_addr_space_end_page + + virt_region.zip(phys_region).each do |virt_page, phys_page| + desc = page_descriptor_from(virt_page) + set_lvl3_entry(desc, phys_page, attributes) + end + end + + def to_binary + data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) + data.pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr_binary + [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr + @lvl2_phys_start_addr + end + + private + + def do_sanity_checks + raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE + raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? + end + + def new_lvl3(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + temp = CArray.new(start_addr, 8192) do + Stage1PageDescriptor.new + end + start_addr += temp.size_in_byte + + temp + end + end + + def new_lvl2(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + Stage1TableDescriptor.new + end + end + + def populate_lvl2_entries + @lvl2.each_with_index do |descriptor, i| + descriptor.next_level_table_addr = @lvl3[i].phys_start_addr + descriptor.type = Stage1TableDescriptor::Type::TABLE + descriptor.valid = Stage1TableDescriptor::Valid::TRUE + end + end + + def lvl2_lvl3_index_from(addr) + lvl2_index = addr >> Granule512MiB::SHIFT + lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT + + raise unless lvl2_index < @lvl2.size + + [lvl2_index, lvl3_index] + end + + def page_descriptor_from(virt_addr) + lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) + + @lvl3[lvl2_index][lvl3_index] + end + + # rubocop:disable Metrics/MethodLength + def set_attributes(desc, attributes) + case attributes.mem_attributes + when :CacheableDRAM + desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE + desc.attr_indx = MAIR::NORMAL + else + raise 'Invalid input' + end + + desc.ap = case attributes.acc_perms + when :ReadOnly + Stage1PageDescriptor::AP::RO_EL1 + when :ReadWrite + Stage1PageDescriptor::AP::RW_EL1 + else + raise 'Invalid input' + + end + + desc.pxn = if attributes.execute_never + Stage1PageDescriptor::PXN::TRUE + else + Stage1PageDescriptor::PXN::FALSE + end + + desc.uxn = Stage1PageDescriptor::UXN::TRUE + end + # rubocop:enable Metrics/MethodLength + + def set_lvl3_entry(desc, output_addr, attributes) + desc.output_addr = output_addr + desc.af = Stage1PageDescriptor::AF::TRUE + desc.type = Stage1PageDescriptor::Type::PAGE + desc.valid = Stage1PageDescriptor::Valid::TRUE + + set_attributes(desc, attributes) + end +end +end +end diff --git a/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb new file mode 100644 index 000000000..49e6fae91 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Raspberry Pi 3 + 4 +class RaspberryPi + attr_reader :kernel_granule, :kernel_virt_addr_space_size + + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + + def initialize + @kernel_granule = Granule64KiB + + @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') + + @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') + @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( + 'PHYS_KERNEL_TABLES_BASE_ADDR' + ) + end + + def phys_addr_of_kernel_tables + KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) + end + + def kernel_tables_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) + end + + def phys_kernel_tables_base_addr_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) + end + + def phys_addr_space_end_page + x = MEMORY_SRC.grep(/pub const END/) + x = case BSP_TYPE + when :rpi3 + x[0] + when :rpi4 + x[1] + else + raise + end + + x.scan(/\d+/).join.to_i(16) + end +end diff --git a/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb new file mode 100644 index 000000000..743840e00 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb @@ -0,0 +1,179 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +module Granule64KiB + SIZE = 64 * 1024 + SHIFT = Math.log2(SIZE).to_i +end + +module Granule512MiB + SIZE = 512 * 1024 * 1024 + SHIFT = Math.log2(SIZE).to_i + MASK = SIZE - 1 +end + +# Monkey-patch Integer with some helper functions. +class Integer + def power_of_two? + self[0].zero? + end + + def aligned?(alignment) + raise unless alignment.power_of_two? + + (self & (alignment - 1)).zero? + end + + def align_up(alignment) + raise unless alignment.power_of_two? + + (self + alignment - 1) & ~(alignment - 1) + end + + def to_hex_underscore(with_leading_zeros: false) + fmt = with_leading_zeros ? '%016x' : '%x' + value = format(fmt, self).to_s.reverse.scan(/.{4}|.+/).join('_').reverse + + format('0x%s', value) + end +end + +# An array where each value is the start address of a Page. +class MemoryRegion < Array + def initialize(start_addr, size, granule_size) + raise unless start_addr.aligned?(granule_size) + raise unless size.positive? + raise unless (size % granule_size).zero? + + num_pages = size / granule_size + super(num_pages) do |i| + (i * granule_size) + start_addr + end + end +end + +# Collection of memory attributes. +class AttributeFields + attr_reader :mem_attributes, :acc_perms, :execute_never + + def initialize(mem_attributes, acc_perms, execute_never) + @mem_attributes = mem_attributes + @acc_perms = acc_perms + @execute_never = execute_never + end + + def to_s + x = case @mem_attributes + when :CacheableDRAM + 'C' + else + '?' + end + + y = case @acc_perms + when :ReadWrite + 'RW' + when :ReadOnly + 'RO' + else + '??' + end + + z = @execute_never ? 'XN' : 'X ' + + "#{x} #{y} #{z}" + end +end + +# A container that describes a virt-to-phys region mapping. +class MappingDescriptor + @max_section_name_length = 'Sections'.length + + class << self + attr_accessor :max_section_name_length + + def update_max_section_name_length(length) + @max_section_name_length = [@max_section_name_length, length].max + end + end + + attr_reader :name, :virt_region, :phys_region, :attributes + + def initialize(name, virt_region, phys_region, attributes) + @name = name + @virt_region = virt_region + @phys_region = phys_region + @attributes = attributes + end + + def to_s + name = @name.ljust(self.class.max_section_name_length) + virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) + phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) + size = ((@virt_region.size * 65_536) / 1024).to_s.rjust(3) + + "#{name} | #{virt_start} | #{phys_start} | #{size} KiB | #{@attributes}" + end + + def self.print_divider + print ' ' + print '-' * max_section_name_length + puts '--------------------------------------------------------------------' + end + + def self.print_header + print_divider + print ' ' + print 'Sections'.center(max_section_name_length) + print ' ' + print 'Virt Start Addr'.center(21) + print ' ' + print 'Phys Start Addr'.center(21) + print ' ' + print 'Size'.center(7) + print ' ' + print 'Attr'.center(7) + puts + print_divider + end +end + +def kernel_map_binary + mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors + + # Generate_mapping_descriptors updates the header being printed with this call. So it must come + # afterwards. + MappingDescriptor.print_header + + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' + puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end + + MappingDescriptor.print_divider +end + +def kernel_patch_tables(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel table struct at ELF file offset ' + puts BSP.kernel_tables_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.to_binary, BSP.kernel_tables_offset_in_file) +end + +def kernel_patch_base_addr(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel tables physical base address start argument to value ' + print TRANSLATION_TABLES.phys_tables_base_addr.to_hex_underscore + print ' at ELF file offset ' + puts BSP.phys_kernel_tables_base_addr_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.phys_tables_base_addr_binary, + BSP.phys_kernel_tables_base_addr_offset_in_file) +end diff --git a/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb new file mode 100644 index 000000000..5ba78d9df --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + SECTION_FLAG_ALLOC = 2 + + def initialize(kernel_elf_path) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + end + + def machine + @elf.machine.to_sym + end + + def symbol_value(symbol_name) + @symtab_section.symbol_by_name(symbol_name).header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_to_phys(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + translation_offset = segment.header.p_vaddr - segment.header.p_paddr + + virt_addr - translation_offset + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + def sections_in_segment(segment) + head = segment.mem_head + tail = segment.mem_tail + + sections = @elf.each_sections.select do |section| + file_offset = section.header.sh_addr + flags = section.header.sh_flags + + file_offset >= head && file_offset < tail && (flags & SECTION_FLAG_ALLOC != 0) + end + + sections.map(&:name).join(' ') + end + + def select_load_segments + @elf.each_segments.select do |segment| + segment.instance_of?(ELFTools::Segments::LoadSegment) + end + end + + def segment_get_acc_perms(segment) + if segment.readable? && segment.writable? + :ReadWrite + elsif segment.readable? + :ReadOnly + else + :Invalid + end + end + + def update_max_section_name_length(descriptors) + MappingDescriptor.update_max_section_name_length(descriptors.map { |i| i.name.size }.max) + end + + def generate_mapping_descriptors + descriptors = select_load_segments.map do |segment| + # Assume each segment is page aligned. + size = segment.mem_size.align_up(BSP.kernel_granule::SIZE) + virt_start_addr = segment.header.p_vaddr + phys_start_addr = segment.header.p_paddr + acc_perms = segment_get_acc_perms(segment) + execute_never = !segment.executable? + section_names = sections_in_segment(segment) + + virt_region = MemoryRegion.new(virt_start_addr, size, BSP.kernel_granule::SIZE) + phys_region = MemoryRegion.new(phys_start_addr, size, BSP.kernel_granule::SIZE) + attributes = AttributeFields.new(:CacheableDRAM, acc_perms, execute_never) + + MappingDescriptor.new(section_names, virt_region, phys_region, attributes) + end + + update_max_section_name_length(descriptors) + descriptors + end +end diff --git a/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb new file mode 100755 index 000000000..22ab24fd5 --- /dev/null +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb @@ -0,0 +1,46 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'generic' +require_relative 'kernel_elf' +require_relative 'bsp' +require_relative 'arch' + +BSP_TYPE = ARGV[0].to_sym +kernel_elf_path = ARGV[1] + +start = Time.now + +KERNEL_ELF = KernelELF.new(kernel_elf_path) + +BSP = case BSP_TYPE + when :rpi3, :rpi4 + RaspberryPi.new + else + raise + end + +TRANSLATION_TABLES = case KERNEL_ELF.machine + when :AArch64 + Arch::ARMv8::TranslationTable.new + else + raise + end + +kernel_map_binary +kernel_patch_tables(kernel_elf_path) +kernel_patch_base_addr(kernel_elf_path) + +elapsed = Time.now - start + +print 'Finished'.rjust(12).green.bold +puts " in #{elapsed.round(2)}s" diff --git a/16_virtual_mem_part4_higher_half_kernel/.cargo/config.toml b/16_virtual_mem_part4_higher_half_kernel/.cargo/config.toml new file mode 100644 index 000000000..e34764853 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.'cfg(target_os = "none")'] +runner = "target/kernel_test_runner.sh" diff --git a/16_virtual_mem_part4_higher_half_kernel/.vscode/settings.json b/16_virtual_mem_part4_higher_half_kernel/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/16_virtual_mem_part4_higher_half_kernel/Cargo.lock b/16_virtual_mem_part4_higher_half_kernel/Cargo.lock new file mode 100644 index 000000000..52d5b3fb5 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/Cargo.lock @@ -0,0 +1,84 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "mingo" +version = "0.16.0" +dependencies = [ + "aarch64-cpu", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/16_virtual_mem_part4_higher_half_kernel/Cargo.toml b/16_virtual_mem_part4_higher_half_kernel/Cargo.toml new file mode 100644 index 000000000..6480a7276 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +members = [ + "libraries/*", + "kernel" +] + +[profile.release] +lto = true diff --git a/16_virtual_mem_part4_higher_half_kernel/Makefile b/16_virtual_mem_part4_higher_half_kernel/Makefile new file mode 100644 index 000000000..bc23270d0 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/Makefile @@ -0,0 +1,354 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF_RAW = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_RAW_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Translation tables +##------------------------------------------------------------------------------ +TT_TOOL_PATH = tools/translation_table_tool + +KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables +KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) + +KERNEL_ELF = $(KERNEL_ELF_TTABLES) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Precompute the kernel translation tables and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) + $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") + @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF_TTABLES) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null + $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/16_virtual_mem_part4_higher_half_kernel/README.md b/16_virtual_mem_part4_higher_half_kernel/README.md new file mode 100644 index 000000000..8082ab455 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/README.md @@ -0,0 +1,866 @@ +# Tutorial 16 - Virtual Memory Part 4: Higher-Half Kernel + +## tl;dr + +- The time has come: We map and run the kernel from the top of the 64 bit virtual address space! 🥳 + +## Table of Contents + +- [Introduction](#introduction) +- [Implementation](#implementation) + - [Linking Changes](#linking-changes) + - [Position-Independent Boot Code](#position-independent-boot-code) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +A long time in the making, in this tutorial we finally map the kernel to the most significant area +(alternatively: higher-half) of the 64 bit virtual address space. This makes room for future +applications to use the whole of the least significant area of the virtual memory space. + +As has been teased since `tutorial 14`, we will make use of the `AArch64`'s `TTBR1`. Since the +kernel's virtual address space size currently is `1 GiB` (defined in +`bsp/__board_name__/memory/mmu.rs`), `TTBR1` will cover the range from `0xffff_ffff_ffff_ffff` down +to `ffff_ffff_c000_0000` (both inclusive). + +## Implementation + +In `src/memory/mmu.rs`, we extend the `AssociatedTranslationTable` trait with a `TableStartFromTop` +associated type: + +```rust +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] + type TableStartFromTop; + + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; +} +``` + +Architecture specific code in `_arch/aarch64/memory/mmu/translation_table.rs` populates both types +now by making use of a new generic that is added to `FixedSizeTranslationTable`, which defines +whether the covered address space starts from the top or the bottom: + +```rust +pub struct FixedSizeTranslationTable { + ... +``` + +```rust +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromTop = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; + + type TableStartFromBottom = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; +} +``` + +Thanks to this infrastructure, `BSP` Rust code in `bsp/__board_name__/memory/mmu.rs` only needs to +change to this newly introduced type in order to switch from lower half to higher half translation +tables for the kernel: + +```rust +type KernelTranslationTable = + ::TableStartFromTop; +``` + +### Linking Changes + +In the `kernel.ld` linker script, we define a new symbol `__kernel_virt_start_addr` now, which is +the start address of the kernel's virtual address space, calculated as `(u64::MAX - +__kernel_virt_addr_space_size) + 1`. Before the first section definition, we set the linker script's +location counter to this address: + +```ld.s +SECTIONS +{ + . = __kernel_virt_start_addr; + + ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ +``` + +Since we are not identity mapping anymore, we start to make use of the `AT` keyword in the output +section specification: + +```ld.s +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + +/* omitted */ + +SECTIONS +{ + . = __kernel_virt_start_addr; + + /* omitted */ + + __code_start = .; + .text : AT(__rpi_phys_binary_load_addr) +``` + +This will manifest in the kernel ELF `segment` attributes, as can be inspected using the `make +readelf` command: + +```console +$ make readelf + +Program Headers: + Type Offset VirtAddr PhysAddr + FileSiz MemSiz Flags Align + LOAD 0x0000000000010000 0xffffffffc0000000 0x0000000000080000 + 0x000000000000cb08 0x000000000000cb08 R E 0x10000 + LOAD 0x0000000000020000 0xffffffffc0010000 0x0000000000090000 + 0x0000000000030dc0 0x0000000000030de0 RW 0x10000 + LOAD 0x0000000000060000 0xffffffffc0860000 0x0000000000000000 + 0x0000000000000000 0x0000000000080000 RW 0x10000 + + Section to Segment mapping: + Segment Sections... + 00 .text .rodata + 01 .data .bss + 02 .boot_core_stack + +``` + +As you can see, `VirtAddr` and `PhysAddr` are different now, as compared to all the previous +tutorials where they were identical. This information from the `ELF` file will eventually be parsed +by the `translation table tool` and incorporated when compiling the precomputed translation tables. + +You might have noticed that `.text .rodata` and `.boot_core_stack` exchanged places as compared to +previous tutorials. The reason this was done is that with a remapped kernel, this is trivial to do +without affecting the physical layout. This allows us to place an unmapped `guard page` between the +`boot core stack` and the `mmio remap region` in the VA space, which nicely protects the kernel from +stack overflows now: + +```ld.s +/*********************************************************************************************** +* MMIO Remap Reserved +***********************************************************************************************/ +__mmio_remap_start = .; +. += 8 * 1024 * 1024; +__mmio_remap_end_exclusive = .; + +ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + +/*********************************************************************************************** +* Guard Page +***********************************************************************************************/ +. += PAGE_SIZE; + +/*********************************************************************************************** +* Boot Core Stack +***********************************************************************************************/ +.boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) +{ + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ +} :segment_boot_core_stack + +ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") +``` + +Changes in the `_arch` `MMU` driver are minimal, and mostly concerned with configuring `TCR_EL1` for +use with `TTBR1_EL1` now. And of course, setting `TTBR1_EL1` in `fn enable_mmu_and_caching(...)`. + +### Position-Independent Boot Code + +Remember all the fuss that we made about `position-independent code` that will be needed until the +`MMU` is enabled. Let's quickly check what it means for us in reality now: + +In `_arch/aarch64/cpu/boot.rs`, we turn on the `MMU` just before returning from `EL2` to `EL1`. So +by the time the CPU enters `EL1`, virtual memory will be active, and the CPU must therefore use the +new higher-half `virtual addresses` for everything it does. + +Specifically, this means the address from which the CPU should execute upon entering `EL1` (function +`kernel_init()`) must be a valid _virtual address_, same as the stack pointer's address. Both of +them are programmed in function `fn prepare_el2_to_el1_transition(...)`, so we must ensure now that +_link-time_ addresses are used here. For this reason, retrieval of these addresses happens in +`assembly` in `boot.s`, where we can explicitly enforce generation of **absolute** addresses: + +```asm +// Load the _absolute_ addresses of the following symbols. Since the kernel is linked at +// the top of the 64 bit address space, these are effectively virtual addresses. +ADR_ABS x1, __boot_core_stack_end_exclusive +ADR_ABS x2, kernel_init +``` + +Both values are forwarded to the Rust entry point function `_start_rust()`, which in turn forwards +them to `fn prepare_el2_to_el1_transition(...)`. + +One more thing to consider is that we keep on programming the boot core's stack address for `EL2` +using an address that is calculated `PC-relative`, because all the `EL2` code will still run while +virtual memory _is disabled_. As such, we need the "physical" address of the stack, so to speak. + +The previous tutorial also explained that it is not easily possible to compile select files using +`-fpic` in `Rust`. Still, we are doing some function calls in `Rust` before virtual memory is +enabled, so _theoretically_, there is room for failure. However, branches to local code in `AArch64` +are usually generated PC-relative. So it is a small risk worth taking. Should it still fail someday, +at least our automated CI pipeline would give notice when the tests start to fail. + +## Test it + +That's it! We are ready for a higher-half kernel now. Power up your Raspberrys and marvel at those +beautiful (virtual) addresses: + +Raspberry Pi 3: + +```console +$ make chainboot +[...] + +Precomputing kernel translation tables and patching kernel ELF + ------------------------------------------------------------------------------------ + Sections Virt Start Addr Phys Start Addr Size Attr + ------------------------------------------------------------------------------------ + Generating .text .rodata | 0xffff_ffff_c000_0000 | 0x0000_0000_0008_0000 | 64 KiB | C RO X + Generating .data .bss | 0xffff_ffff_c001_0000 | 0x0000_0000_0009_0000 | 256 KiB | C RW XN + Generating .boot_core_stack | 0xffff_ffff_c086_0000 | 0x0000_0000_0000_0000 | 512 KiB | C RW XN + ------------------------------------------------------------------------------------ + Patching Kernel table struct at ELF file offset 0x2_0000 + Patching Kernel tables physical base address start argument to value 0xb_0000 at ELF file offset 0x1_0088 + Finished in 0.14s + +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 +[ML] Loaded! Executing the payload now + +[ 2.870248] mingo version 0.16.0 +[ 2.870456] Booting on: Raspberry Pi 3 +[ 2.870911] MMU online: +[ 2.871203] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 2.872947] Virtual Physical Size Attr Entity +[ 2.874691] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 2.876436] 0xffff_ffff_c000_0000..0xffff_ffff_c000_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data +[ 2.878050] 0xffff_ffff_c001_0000..0xffff_ffff_c004_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss +[ 2.879621] 0xffff_ffff_c005_0000..0xffff_ffff_c005_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART +[ 2.881137] | BCM GPIO +[ 2.882589] 0xffff_ffff_c006_0000..0xffff_ffff_c006_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Interrupt Controller +[ 2.884214] 0xffff_ffff_c086_0000..0xffff_ffff_c08d_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack +[ 2.885818] ------------------------------------------------------------------------------------------------------------------------------------------- +``` + +Raspberry Pi 4: + +```console +$ BSP=rpi4 make chainboot +[...] + +Precomputing kernel translation tables and patching kernel ELF + ------------------------------------------------------------------------------------ + Sections Virt Start Addr Phys Start Addr Size Attr + ------------------------------------------------------------------------------------ + Generating .text .rodata | 0xffff_ffff_c000_0000 | 0x0000_0000_0008_0000 | 64 KiB | C RO X + Generating .data .bss | 0xffff_ffff_c001_0000 | 0x0000_0000_0009_0000 | 256 KiB | C RW XN + Generating .boot_core_stack | 0xffff_ffff_c086_0000 | 0x0000_0000_0000_0000 | 512 KiB | C RW XN + ------------------------------------------------------------------------------------ + Patching Kernel table struct at ELF file offset 0x2_0000 + Patching Kernel tables physical base address start argument to value 0xb_0000 at ELF file offset 0x1_0080 + Finished in 0.13s + +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 4 + +[ML] Requesting binary +[MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 +[ML] Loaded! Executing the payload now + +[ 2.871960] mingo version 0.16.0 +[ 2.871994] Booting on: Raspberry Pi 4 +[ 2.872449] MMU online: +[ 2.872742] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 2.874486] Virtual Physical Size Attr Entity +[ 2.876230] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 2.877975] 0xffff_ffff_c000_0000..0xffff_ffff_c000_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data +[ 2.879589] 0xffff_ffff_c001_0000..0xffff_ffff_c004_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss +[ 2.881159] 0xffff_ffff_c005_0000..0xffff_ffff_c005_ffff --> 0x00_fe20_0000..0x00_fe20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART +[ 2.882676] | BCM GPIO +[ 2.884128] 0xffff_ffff_c006_0000..0xffff_ffff_c006_ffff --> 0x00_ff84_0000..0x00_ff84_ffff | 64 KiB | Dev RW XN | GICv2 GICD +[ 2.885601] | GICV2 GICC +[ 2.887074] 0xffff_ffff_c086_0000..0xffff_ffff_c08d_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack +[ 2.888678] ------------------------------------------------------------------------------------------------------------------------------------------- +``` + +## Diff to previous +```diff + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml 16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml +--- 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.15.0" ++version = "0.16.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs +@@ -34,7 +34,10 @@ + /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. + /// - The HW state of EL1 must be prepared in a sound way. + #[inline(always)] +-unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { ++unsafe fn prepare_el2_to_el1_transition( ++ virt_boot_core_stack_end_exclusive_addr: u64, ++ virt_kernel_init_addr: u64, ++) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + +@@ -57,11 +60,11 @@ + ); + + // Second, let the link register point to kernel_init(). +- ELR_EL2.set(crate::kernel_init as *const () as u64); ++ ELR_EL2.set(virt_kernel_init_addr); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. +- SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); ++ SP_EL1.set(virt_boot_core_stack_end_exclusive_addr); + } + + //-------------------------------------------------------------------------------------------------- +@@ -78,14 +81,19 @@ + #[no_mangle] + pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, +- phys_boot_core_stack_end_exclusive_addr: u64, ++ virt_boot_core_stack_end_exclusive_addr: u64, ++ virt_kernel_init_addr: u64, + ) -> ! { +- prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); ++ prepare_el2_to_el1_transition( ++ virt_boot_core_stack_end_exclusive_addr, ++ virt_kernel_init_addr, ++ ); + + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + +- // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. ++ // Use `eret` to "return" to EL1. Since virtual memory will already be enabled, this results in ++ // execution of kernel_init() in EL1 from its _virtual address_. + asm::eret() + } + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s +@@ -18,6 +18,18 @@ + add \register, \register, #:lo12:\symbol + .endm + ++// Load the address of a symbol into a register, absolute. ++// ++// # Resources ++// ++// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html ++.macro ADR_ABS register, symbol ++ movz \register, #:abs_g3:\symbol ++ movk \register, #:abs_g2_nc:\symbol ++ movk \register, #:abs_g1_nc:\symbol ++ movk \register, #:abs_g0_nc:\symbol ++.endm ++ + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -56,19 +68,31 @@ + // Load the base address of the kernel's translation tables. + ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + +- // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. +- ADR_REL x1, __boot_core_stack_end_exclusive +- mov sp, x1 ++ // Load the _absolute_ addresses of the following symbols. Since the kernel is linked at ++ // the top of the 64 bit address space, these are effectively virtual addresses. ++ ADR_ABS x1, __boot_core_stack_end_exclusive ++ ADR_ABS x2, kernel_init ++ ++ // Load the PC-relative address of the stack and set the stack pointer. ++ // ++ // Since _start() is the first function that runs after the firmware has loaded the kernel ++ // into memory, retrieving this symbol PC-relative returns the "physical" address. ++ // ++ // Setting the stack pointer to this value ensures that anything that still runs in EL2, ++ // until the kernel returns to EL1 with the MMU enabled, works as well. After the return to ++ // EL1, the virtual address of the stack retrieved above will be used. ++ ADR_REL x3, __boot_core_stack_end_exclusive ++ mov sp, x3 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. +- ADR_REL x2, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs +- mrs x3, CNTFRQ_EL0 +- cmp x3, xzr ++ ADR_REL x4, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs ++ mrs x5, CNTFRQ_EL0 ++ cmp x5, xzr + b.eq .L_parking_loop +- str w3, [x2] ++ str w5, [x4] + +- // Jump to Rust code. x0 and x1 hold the function arguments provided to _start_rust(). ++ // Jump to Rust code. x0, x1 and x2 hold the function arguments provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +@@ -136,7 +136,7 @@ + /// aligned, so the lvl3 is put first. + #[repr(C)] + #[repr(align(65536))] +-pub struct FixedSizeTranslationTable { ++pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + +@@ -302,10 +302,19 @@ + where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, + { +- type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }>; ++ type TableStartFromTop = ++ FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; ++ ++ type TableStartFromBottom = ++ FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; + } + +-impl FixedSizeTranslationTable { ++impl ++ FixedSizeTranslationTable ++{ ++ const START_FROM_TOP_OFFSET: Address = ++ Address::new((usize::MAX - (Granule512MiB::SIZE * NUM_TABLES)) + 1); ++ + /// Create an instance. + #[allow(clippy::assertions_on_constants)] + const fn _new(for_precompute: bool) -> Self { +@@ -336,9 +345,14 @@ + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { +- let addr = virt_page_addr.into_inner().as_usize(); +- let lvl2_index = addr >> Granule512MiB::SHIFT; +- let lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT; ++ let mut addr = virt_page_addr.into_inner(); ++ ++ if START_FROM_TOP { ++ addr = addr - Self::START_FROM_TOP_OFFSET; ++ } ++ ++ let lvl2_index = addr.as_usize() >> Granule512MiB::SHIFT; ++ let lvl3_index = (addr.as_usize() & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); +@@ -384,8 +398,9 @@ + // OS Interface Code + //------------------------------------------------------------------------------ + +-impl memory::mmu::translation_table::interface::TranslationTable +- for FixedSizeTranslationTable ++impl ++ memory::mmu::translation_table::interface::TranslationTable ++ for FixedSizeTranslationTable + { + fn init(&mut self) -> Result<(), &'static str> { + if self.initialized { +@@ -479,7 +494,7 @@ + //-------------------------------------------------------------------------------------------------- + + #[cfg(test)] +-pub type MinSizeTranslationTable = FixedSizeTranslationTable<1>; ++pub type MinSizeTranslationTable = FixedSizeTranslationTable<1, true>; + + #[cfg(test)] + mod tests { + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs +@@ -66,6 +66,7 @@ + + impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. ++ #[inline(always)] + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( +@@ -79,20 +80,21 @@ + } + + /// Configure various settings of stage 1 of the EL1 translation regime. ++ #[inline(always)] + fn configure_translation_control(&self) { +- let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; ++ let t1sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( +- TCR_EL1::TBI0::Used ++ TCR_EL1::TBI1::Used + + TCR_EL1::IPS::Bits_40 +- + TCR_EL1::TG0::KiB_64 +- + TCR_EL1::SH0::Inner +- + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable +- + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable +- + TCR_EL1::EPD0::EnableTTBR0Walks +- + TCR_EL1::A1::TTBR0 +- + TCR_EL1::T0SZ.val(t0sz) +- + TCR_EL1::EPD1::DisableTTBR1Walks, ++ + TCR_EL1::TG1::KiB_64 ++ + TCR_EL1::SH1::Inner ++ + TCR_EL1::ORGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable ++ + TCR_EL1::IRGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable ++ + TCR_EL1::EPD1::EnableTTBR1Walks ++ + TCR_EL1::A1::TTBR1 ++ + TCR_EL1::T1SZ.val(t1sz) ++ + TCR_EL1::EPD0::DisableTTBR0Walks, + ); + } + } +@@ -131,7 +133,7 @@ + self.set_up_mair(); + + // Set the "Translation Table Base Register". +- TTBR0_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); ++ TTBR1_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld +@@ -8,6 +8,13 @@ + PAGE_SIZE = 64K; + PAGE_MASK = PAGE_SIZE - 1; + ++/* The kernel's virtual address range will be: ++ * ++ * [END_ADDRESS_INCLUSIVE, START_ADDRESS] ++ * [u64::MAX , (u64::MAX - __kernel_virt_addr_space_size) + 1] ++ */ ++__kernel_virt_start_addr = ((0xffffffffffffffff - __kernel_virt_addr_space_size) + 1); ++ + __rpi_phys_dram_start_addr = 0; + + /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +@@ -26,34 +33,22 @@ + */ + PHDRS + { +- segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); ++ segment_boot_core_stack PT_LOAD FLAGS(6); + } + + SECTIONS + { +- . = __rpi_phys_dram_start_addr; +- +- /*********************************************************************************************** +- * Boot Core Stack +- ***********************************************************************************************/ +- .boot_core_stack (NOLOAD) : +- { +- __boot_core_stack_start = .; /* ^ */ +- /* | stack */ +- . += __rpi_phys_binary_load_addr; /* | growth */ +- /* | direction */ +- __boot_core_stack_end_exclusive = .; /* | */ +- } :segment_boot_core_stack ++ . = __kernel_virt_start_addr; + +- ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") ++ ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; +- .text : ++ .text : AT(__rpi_phys_binary_load_addr) + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ +@@ -91,6 +86,25 @@ + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + ++ ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") ++ ++ /*********************************************************************************************** ++ * Guard Page ++ ***********************************************************************************************/ ++ . += PAGE_SIZE; ++ ++ /*********************************************************************************************** ++ * Boot Core Stack ++ ***********************************************************************************************/ ++ .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) ++ { ++ __boot_core_stack_start = .; /* ^ */ ++ /* | stack */ ++ . += __rpi_phys_binary_load_addr; /* | growth */ ++ /* | direction */ ++ __boot_core_stack_end_exclusive = .; /* | */ ++ } :segment_boot_core_stack ++ + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs +@@ -20,7 +20,7 @@ + //-------------------------------------------------------------------------------------------------- + + type KernelTranslationTable = +- ::TableStartFromBottom; ++ ::TableStartFromTop; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions +@@ -153,14 +153,6 @@ + /// `translation table tool` and patched into the kernel binary. This function just adds the mapping + /// record entries. + pub fn kernel_add_mapping_records_for_precomputed() { +- let virt_boot_core_stack_region = virt_boot_core_stack_region(); +- generic_mmu::kernel_add_mapping_record( +- "Kernel boot-core stack", +- &virt_boot_core_stack_region, +- &kernel_virt_to_phys_region(virt_boot_core_stack_region), +- &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), +- ); +- + let virt_code_region = virt_code_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel code and RO data", +@@ -176,4 +168,12 @@ + &kernel_virt_to_phys_region(virt_data_region), + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); ++ ++ let virt_boot_core_stack_region = virt_boot_core_stack_region(); ++ generic_mmu::kernel_add_mapping_record( ++ "Kernel boot-core stack", ++ &virt_boot_core_stack_region, ++ &kernel_virt_to_phys_region(virt_boot_core_stack_region), ++ &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), ++ ); + } + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs +@@ -37,13 +37,7 @@ + //! The virtual memory layout is as follows: + //! + //! +---------------------------------------+ +-//! | | boot_core_stack_start @ 0x0 +-//! | | ^ +-//! | Boot-core Stack | | stack +-//! | | | growth +-//! | | | direction +-//! +---------------------------------------+ +-//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive ++//! | | code_start @ __kernel_virt_start_addr + //! | .text | + //! | .rodata | + //! | .got | +@@ -59,6 +53,16 @@ + //! | | + //! +---------------------------------------+ + //! | | mmio_remap_end_exclusive ++//! | Unmapped guard page | ++//! | | ++//! +---------------------------------------+ ++//! | | boot_core_stack_start ++//! | | ^ ++//! | Boot-core Stack | | stack ++//! | | | growth ++//! | | | direction ++//! +---------------------------------------+ ++//! | | boot_core_stack_end_exclusive + //! | | + pub mod mmu; + + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs +@@ -157,11 +157,6 @@ + ) + } + +-#[cfg(not(test))] +-extern "Rust" { +- fn kernel_init() -> !; +-} +- + //-------------------------------------------------------------------------------------------------- + // Testing + //-------------------------------------------------------------------------------------------------- + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs +@@ -99,9 +99,9 @@ + + assert_eq!(tables.init(), Ok(())); + +- let virt_start_page_addr: PageAddress = PageAddress::from(0); +- let virt_end_exclusive_page_addr: PageAddress = +- virt_start_page_addr.checked_offset(5).unwrap(); ++ let virt_end_exclusive_page_addr: PageAddress = PageAddress::MAX; ++ let virt_start_page_addr: PageAddress = ++ virt_end_exclusive_page_addr.checked_offset(-5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = +@@ -124,7 +124,7 @@ + ); + + assert_eq!( +- tables.try_page_attributes(virt_start_page_addr.checked_offset(6).unwrap()), ++ tables.try_page_attributes(virt_start_page_addr.checked_offset(-1).unwrap()), + Err("Page marked invalid") + ); + + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs +@@ -67,6 +67,11 @@ + // PageAddress + //------------------------------------------------------------------------------ + impl PageAddress { ++ /// The largest value that can be represented by this type. ++ pub const MAX: Self = PageAddress { ++ inner: Address::new(usize::MAX).align_down_page(), ++ }; ++ + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs +@@ -66,6 +66,11 @@ + pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// ++ /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] ++ type TableStartFromTop; ++ ++ /// A translation table whose address range is: ++ /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; + } + +diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs 16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs +--- 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs ++++ 16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs +@@ -28,8 +28,8 @@ + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + +- info!("Writing beyond mapped area to address 9 GiB..."); +- let big_addr: u64 = 9 * 1024 * 1024 * 1024; ++ info!("Writing to bottom of address space to address 1 GiB..."); ++ let big_addr: u64 = 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + +diff -uNr 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb +--- 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb ++++ 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb +@@ -255,6 +255,8 @@ + end + + def lvl2_lvl3_index_from(addr) ++ addr -= BSP.kernel_virt_start_addr ++ + lvl2_index = addr >> Granule512MiB::SHIFT + lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT + + +diff -uNr 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb +--- 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb ++++ 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb +@@ -6,7 +6,7 @@ + + # Raspberry Pi 3 + 4 + class RaspberryPi +- attr_reader :kernel_granule, :kernel_virt_addr_space_size ++ attr_reader :kernel_granule, :kernel_virt_addr_space_size, :kernel_virt_start_addr + + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + +@@ -14,6 +14,7 @@ + @kernel_granule = Granule64KiB + + @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') ++ @kernel_virt_start_addr = KERNEL_ELF.symbol_value('__kernel_virt_start_addr') + + @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') + @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( + +``` diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml b/16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml new file mode 100644 index 000000000..857256cb6 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml @@ -0,0 +1,57 @@ +[package] +name = "mingo" +version = "0.16.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##-------------------------------------------------------------------------------------------------- +## Testing +##-------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/build.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..4d7b77357 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use crate::{memory, memory::Address}; +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(virt_kernel_init_addr); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(virt_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) -> ! { + prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr, + virt_kernel_init_addr, + ); + + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + + // Use `eret` to "return" to EL1. Since virtual memory will already be enabled, this results in + // execution of kernel_init() in EL1 from its _virtual address_. + asm::eret() +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..1a8c88010 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +// Load the address of a symbol into a register, absolute. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_ABS register, symbol + movz \register, #:abs_g3:\symbol + movk \register, #:abs_g2_nc:\symbol + movk \register, #:abs_g1_nc:\symbol + movk \register, #:abs_g0_nc:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Load the base address of the kernel's translation tables. + ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + + // Load the _absolute_ addresses of the following symbols. Since the kernel is linked at + // the top of the 64 bit address space, these are effectively virtual addresses. + ADR_ABS x1, __boot_core_stack_end_exclusive + ADR_ABS x2, kernel_init + + // Load the PC-relative address of the stack and set the stack pointer. + // + // Since _start() is the first function that runs after the firmware has loaded the kernel + // into memory, retrieving this symbol PC-relative returns the "physical" address. + // + // Setting the stack pointer to this value ensures that anything that still runs in EL2, + // until the kernel returns to EL1 with the MMU enabled, works as well. After the return to + // EL1, the virtual address of the stack retrieved above will be used. + ADR_REL x3, __boot_core_stack_end_exclusive + mov sp, x3 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x4, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x5, CNTFRQ_EL0 + cmp x5, xzr + b.eq .L_parking_loop + str w5, [x4] + + // Jump to Rust code. x0, x1 and x2 hold the function arguments provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/smp.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/smp.rs new file mode 100644 index 000000000..491920389 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..730198009 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use crate::exception; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!(include_str!("exception.s")); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.s b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..91805ee7c --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 17 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception/asynchronous.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..811ef138e --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..984b2e04f --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::{mmu::TranslationGranule, Address, Physical}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + #[inline(always)] + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + #[inline(always)] + fn configure_translation_control(&self) { + let t1sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI1::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG1::KiB_64 + + TCR_EL1::SH1::Inner + + TCR_EL1::ORGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD1::EnableTTBR1Walks + + TCR_EL1::A1::TTBR1 + + TCR_EL1::T1SZ.val(t1sz) + + TCR_EL1::EPD0::DisableTTBR0Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Set the "Translation Table Base Register". + TTBR1_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..21fae3b82 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,521 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, + memory::{ + self, + mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, + }, + Address, Physical, Virtual, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn virt_start_addr(&self) -> Address; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], + + /// Have the tables been initialized? + initialized: bool, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl StartAddr for [T; N] { + fn virt_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +/// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. +impl convert::TryFrom> for AttributeFields { + type Error = &'static str; + + fn try_from( + desc: InMemoryRegister, + ) -> Result { + let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { + memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, + memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, + _ => return Err("Unexpected memory attribute"), + }; + + let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, + _ => return Err("Unexpected access permission"), + }; + + let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; + + Ok(AttributeFields { + mem_attributes, + acc_perms, + execute_never, + }) + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_page_addr( + phys_output_page_addr: PageAddress, + attribute_fields: &AttributeFields, + ) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } + + /// Returns the valid bit. + fn is_valid(&self) -> bool { + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } + + /// Returns the output page. + fn output_page_addr(&self) -> PageAddress { + let shifted = InMemoryRegister::::new(self.value) + .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; + + PageAddress::from(shifted << Granule64KiB::SHIFT) + } + + /// Returns the attributes. + fn try_attributes(&self) -> Result { + InMemoryRegister::::new(self.value).try_into() + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromTop = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; + + type TableStartFromBottom = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; +} + +impl + FixedSizeTranslationTable +{ + const START_FROM_TOP_OFFSET: Address = + Address::new((usize::MAX - (Granule512MiB::SIZE * NUM_TABLES)) + 1); + + /// Create an instance. + #[allow(clippy::assertions_on_constants)] + const fn _new(for_precompute: bool) -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + initialized: for_precompute, + } + } + + pub const fn new_for_precompute() -> Self { + Self::_new(true) + } + + #[cfg(test)] + pub fn new_for_runtime() -> Self { + Self::_new(false) + } + + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { + let mut addr = virt_page_addr.into_inner(); + + if START_FROM_TOP { + addr = addr - Self::START_FROM_TOP_OFFSET; + } + + let lvl2_index = addr.as_usize() >> Granule512MiB::SHIFT; + let lvl3_index = (addr.as_usize() & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); + } + + Ok((lvl2_index, lvl3_index)) + } + + /// Returns the PageDescriptor corresponding to the supplied page address. + #[inline(always)] + fn page_descriptor_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<&PageDescriptor, &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &self.lvl3[lvl2_index][lvl3_index]; + + Ok(desc) + } + + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. + #[inline(always)] + fn set_page_descriptor_from_page_addr( + &mut self, + virt_page_addr: PageAddress, + new_desc: &PageDescriptor, + ) -> Result<(), &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &mut self.lvl3[lvl2_index][lvl3_index]; + + if desc.is_valid() { + return Err("Virtual page is already mapped"); + } + + *desc = *new_desc; + Ok(()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl + memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable +{ + fn init(&mut self) -> Result<(), &'static str> { + if self.initialized { + return Ok(()); + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { + let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); + let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; + + Ok(()) + } + + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + assert!(self.initialized, "Translation tables not initialized"); + + if virt_region.size() != phys_region.size() { + return Err("Tried to map memory regions with unequal sizes"); + } + + if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() + { + return Err("Tried to map outside of physical address space"); + } + + let iter = phys_region.into_iter().zip(virt_region.into_iter()); + for (phys_page_addr, virt_page_addr) in iter { + let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); + let virt_page = virt_page_addr; + + self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; + } + + Ok(()) + } + + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str> { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + Ok(page_desc.output_page_addr()) + } + + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + page_desc.try_attributes() + } + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str> { + let virt_page = PageAddress::from(virt_addr.align_down_page()); + let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; + + Ok(phys_page.into_inner() + virt_addr.offset_into_page()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1, true>; + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/time.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..2dfaec8d6 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(feature = "bsp_rpi4")] +mod arm; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm.rs new file mode 100644 index 000000000..8d1cbfbd8 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2.rs new file mode 100644 index 000000000..256de7041 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new( + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, + ) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs new file mode 100644 index 000000000..0fd16bb38 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs new file mode 100644 index 000000000..1fc9d70e9 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, + state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num % 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..7b7c288b7 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..812156f44 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs new file mode 100644 index 000000000..62f078002 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.periph.print_handler(); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs new file mode 100644 index 000000000..a26bff8d0 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), + } + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() % 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..b424d4be7 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/common.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..3ce1d8d81 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use crate::memory::{Address, Virtual}; +use core::{fmt, marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: Address, + phantom: PhantomData T>, +} + +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: Address) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr.as_usize() as *const _) } + } +} + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..30421dfa6 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/cpu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/driver.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..a1f55b170 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, + memory, + memory::mmu::MMIODescriptor, +}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering}, +}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi3")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi4")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the UART driver. +unsafe fn post_init_uart() -> Result<(), &'static str> { + console::register_console(PL011_UART.assume_init_ref()); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_gpio() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; + + GPIO.write(device_driver::GPIO::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +unsafe fn post_init_gpio() -> Result<(), &'static str> { + GPIO.assume_init_ref().map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi3")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &periph_mmio_descriptor, + )?; + + INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi4")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); + let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; + + let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); + let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; + + INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the interrupt controller driver. +unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_gpio() -> Result<(), &'static str> { + instantiate_gpio()?; + + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( + GPIO.assume_init_ref(), + Some(post_init_gpio), + None, + ); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { + instantiate_interrupt_controller()?; + + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + INTERRUPT_CONTROLLER.assume_init_ref(), + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + use crate::cpu; + + unsafe { + instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); + console::register_console(PL011_UART.assume_init_ref()); + }; +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception.rs new file mode 100644 index 000000000..a9eaa6ac4 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception/asynchronous.rs new file mode 100644 index 000000000..776182fd0 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +#[cfg(feature = "bsp_rpi3")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; + + pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +#[cfg(feature = "bsp_rpi4")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::IRQNumber; + + pub const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..c17b61f9e --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,117 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +INCLUDE kernel_virt_addr_space_size.ld; + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +/* The kernel's virtual address range will be: + * + * [END_ADDRESS_INCLUSIVE, START_ADDRESS] + * [u64::MAX , (u64::MAX - __kernel_virt_addr_space_size) + 1] + */ +__kernel_virt_start_addr = ((0xffffffffffffffff - __kernel_virt_addr_space_size) + 1); + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); + segment_boot_core_stack PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __kernel_virt_start_addr; + + ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : AT(__rpi_phys_binary_load_addr) + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + __data_start = .; + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + + /*********************************************************************************************** + * Guard Page + ***********************************************************************************************/ + . += PAGE_SIZE; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) + { + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld new file mode 100644 index 000000000..c5d58c30a --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld @@ -0,0 +1 @@ +__kernel_virt_addr_space_size = 1024 * 1024 * 1024 diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..3a33126c3 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | data_end_exclusive +//! | | +//! +//! +//! +//! +//! +//! The virtual memory layout is as follows: +//! +//! +---------------------------------------+ +//! | | code_start @ __kernel_virt_start_addr +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_start == data_end_exclusive +//! | VA region for MMIO remapping | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_end_exclusive +//! | Unmapped guard page | +//! | | +//! +---------------------------------------+ +//! | | boot_core_stack_start +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | boot_core_stack_end_exclusive +//! | | +pub mod mmu; + +use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; + + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + + static __boot_core_stack_start: UnsafeCell<()>; + static __boot_core_stack_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + use super::*; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); + pub const PERIPHERAL_IC_SIZE: usize = 0x24; + + pub const GPIO_START: Address = Address::new(0x3F20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const END: Address = Address::new(0x4001_0000); + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const GPIO_START: Address = Address::new(0xFE20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0xFE20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const GICD_START: Address = Address::new(0xFF84_1000); + pub const GICD_SIZE: usize = 0x824; + + pub const GICC_START: Address = Address::new(0xFF84_2000); + pub const GICC_SIZE: usize = 0x14; + + pub const END: Address = Address::new(0xFF85_0000); + } + + pub const END: Address = mmio::END; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_code_start() -> PageAddress { + PageAddress::from(unsafe { __code_start.get() as usize }) +} + +/// Size of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_size() -> usize { + unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } +} + +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { + PageAddress::from(unsafe { __data_start.get() as usize }) +} + +/// Size of the data segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn data_size() -> usize { + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } +} + +/// Start page address of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_mmio_remap_start() -> PageAddress { + PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) +} + +/// Size of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn mmio_remap_size() -> usize { + unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } +} + +/// Start page address of the boot core's stack. +#[inline(always)] +fn virt_boot_core_stack_start() -> PageAddress { + PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) +} + +/// Size of the boot core's stack. +#[inline(always)] +fn boot_core_stack_size() -> usize { + unsafe { + (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Exclusive end address of the physical address space. +#[inline(always)] +pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { + PageAddress::from(map::END) +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..3c0368b91 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use crate::{ + memory::{ + mmu::{ + self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, + MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type KernelTranslationTable = + ::TableStartFromTop; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to +/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. +pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + +/// The kernel's virtual address space defined by this BSP. +pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// It is mandatory that InitStateLock is transparent. +/// +/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. +/// There is a unit tests that checks this porperty. +#[link_section = ".data"] +#[no_mangle] +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new_for_precompute()); + +/// This value is needed during early boot for MMU setup. +/// +/// This will be patched to the correct value by the "translation table tool" after linking. This +/// given value here is just a dummy. +#[link_section = ".text._start_arguments"] +#[no_mangle] +static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This is a hack for retrieving the value for the kernel's virtual address space size as a +/// constant from a common place, since it is needed as a compile-time/link-time constant in both, +/// the linker script and the Rust sources. +#[allow(clippy::needless_late_init)] +const fn kernel_virt_addr_space_size() -> usize { + let __kernel_virt_addr_space_size; + + include!("../kernel_virt_addr_space_size.ld"); + + __kernel_virt_addr_space_size +} + +/// Helper function for calculating the number of pages the given parameter spans. +const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); + assert!(size % KernelGranule::SIZE == 0); + + size >> KernelGranule::SHIFT +} + +/// The code pages of the kernel binary. +fn virt_code_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::code_size()); + + let start_page_addr = super::virt_code_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The data pages of the kernel binary. +fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); + + let start_page_addr = super::virt_data_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The boot core stack pages. +fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); + + let start_page_addr = super::virt_boot_core_stack_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +// There is no reason to expect the following conversions to fail, since they were generated offline +// by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. +fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { + let phys_start_page_addr = + generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) + .unwrap(); + + let phys_end_exclusive_page_addr = phys_start_page_addr + .checked_offset(virt_region.num_pages() as isize) + .unwrap(); + + MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) +} + +fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { + generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} + +/// The MMIO remap pages. +pub fn virt_mmio_remap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::mmio_remap_size()); + + let start_page_addr = super::virt_mmio_remap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Add mapping records for the kernel binary. +/// +/// The actual translation table entries for the kernel binary are generated using the offline +/// `translation table tool` and patched into the kernel binary. This function just adds the mapping +/// record entries. +pub fn kernel_add_mapping_records_for_precomputed() { + let virt_code_region = virt_code_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel code and RO data", + &virt_code_region, + &kernel_virt_to_phys_region(virt_code_region), + &kernel_page_attributes(virt_code_region.start_page_addr()), + ); + + let virt_data_region = virt_data_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel data and bss", + &virt_data_region, + &kernel_virt_to_phys_region(virt_data_region), + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); + + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", + &virt_boot_core_stack_region, + &kernel_virt_to_phys_region(virt_boot_core_stack_region), + &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), + ); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/common.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/common.rs new file mode 100644 index 000000000..2ad7e4c1e --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/common.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Check if a value is aligned to a given size. +#[inline(always)] +pub const fn is_aligned(value: usize, alignment: usize) -> bool { + assert!(alignment.is_power_of_two()); + + (value & (alignment - 1)) == 0 +} + +/// Align down. +#[inline(always)] +pub const fn align_down(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + value & !(alignment - 1) +} + +/// Align up. +#[inline(always)] +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + (value + alignment - 1) & !(alignment - 1) +} + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/console.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/console.rs new file mode 100644 index 000000000..f03634649 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.read(|con| *con) +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/console/null_console.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu.rs new file mode 100644 index 000000000..8716a918b --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +pub mod smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/boot.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/smp.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/smp.rs new file mode 100644 index 000000000..de612d589 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/driver.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/driver.rs new file mode 100644 index 000000000..2edf8b854 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/driver.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner +where + T: 'static, +{ + next_index: usize, + descriptors: [Option>; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager +where + T: 'static, +{ + inner: InitStateLock>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner +where + T: 'static + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + irq_number, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager +where + T: fmt::Display + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: InitStateLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.write(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.read(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + self.for_each_descriptor(|descriptor| { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..2c874dd60 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous/null_irq_manager.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous/null_irq_manager.rs new file mode 100644 index 000000000..38919ffe4 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs new file mode 100644 index 000000000..d883d354e --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(generic_const_exprs)] +#![feature(int_roundings)] +#![feature(is_sorted)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(step_trait)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +mod panic_wait; +mod synchronization; + +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod state; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/main.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/main.rs new file mode 100644 index 000000000..e41cfaa0d --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/main.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + +/// Early init code. +/// +/// When this code runs, virtual memory is already enabled. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - Printing will not work until the respective driver's MMIO is remapped. +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + + bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online:"); + memory::mmu::kernel_print_mappings(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + + info!("Echoing input now"); + cpu::wait_forever(); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory.rs new file mode 100644 index 000000000..6131bdb6c --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; + +use crate::{bsp, common}; +use core::{ + fmt, + marker::PhantomData, + ops::{Add, Sub}, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Physical {} + +/// Zero-sized type to mark a virtual address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl AddressType for Physical {} +impl AddressType for Virtual {} + +impl Address { + /// Create an instance. + pub const fn new(value: usize) -> Self { + Self { + value, + _address_type: PhantomData, + } + } + + /// Convert to usize. + pub const fn as_usize(self) -> usize { + self.value + } + + /// Align down to page size. + #[must_use] + pub const fn align_down_page(self) -> Self { + let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Align up to page size. + #[must_use] + pub const fn align_up_page(self) -> Self { + let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Checks if the address is page aligned. + pub const fn is_page_aligned(&self) -> bool { + common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) + } + + /// Return the address' offset into the corresponding page. + pub const fn offset_into_page(&self) -> usize { + self.value & bsp::memory::mmu::KernelGranule::MASK + } +} + +impl Add for Address { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: usize) -> Self::Output { + match self.value.checked_add(rhs) { + None => panic!("Overflow on Address::add"), + Some(x) => Self::new(x), + } + } +} + +impl Sub> for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Address) -> Self::Output { + match self.value.checked_sub(rhs.value) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q3: u8 = ((self.value >> 32) & 0xff) as u8; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:02x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q4: u16 = ((self.value >> 48) & 0xffff) as u16; + let q3: u16 = ((self.value >> 32) & 0xffff) as u16; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:04x}_", q4)?; + write!(f, "{:04x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of [Address] methods. + #[kernel_test] + fn address_type_method_sanity() { + let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); + + assert_eq!( + addr.align_down_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE + ); + + assert_eq!( + addr.align_up_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + + assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..404e2a8a9 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs @@ -0,0 +1,265 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod mapping_record; +mod page_alloc; +mod translation_table; +mod types; + +use crate::{ + bsp, + memory::{Address, Physical, Virtual}, + synchronization::{self, interface::Mutex}, + warn, +}; +use core::{fmt, num::NonZeroUsize}; + +pub use types::*; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Turns on the MMU for the first time and enables data and instruction caching. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] + type TableStartFromTop; + + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +use interface::MMU; +use synchronization::interface::ReadWriteEx; +use translation_table::interface::TranslationTable; + +/// Map a region in the kernel's translation tables. +/// +/// No input checks done, input is passed through to the architectural implementation. +/// +/// # Safety +/// +/// - See `map_at()`. +/// - Does not prevent aliasing. +unsafe fn kernel_map_at_unchecked( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + + kernel_add_mapping_record(name, virt_region, phys_region, attr); + + Ok(()) +} + +/// Try to translate a kernel virtual address to a physical address. +/// +/// Will only succeed if there exists a valid mapping for the input address. +fn try_kernel_virt_addr_to_phys_addr( + virt_addr: Address, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's mask. + pub const MASK: usize = Self::SIZE - 1; + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +pub fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Add an entry to the mapping info record. +pub fn kernel_add_mapping_record( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) { + if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { + warn!("{}", x); + } +} + +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +/// +/// # Safety +/// +/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + let phys_region = MemoryRegion::from(*mmio_descriptor); + let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); + + // Check if an identical region has been mapped for another driver. If so, reuse it. + let virt_addr = if let Some(addr) = + mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) + { + addr + // Otherwise, allocate a new region and map it. + } else { + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, + }; + + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + virt_region.start_addr() + }; + + Ok(virt_addr + offset_into_start_page) +} + +/// Try to translate a kernel virtual page address to a physical page address. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_virt_page_addr_to_phys_page_addr( + virt_page_addr: PageAddress, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) +} + +/// Try to get the attributes of a kernel page. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_page_attributes( + virt_page_addr: PageAddress, +) -> Result { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_page_attributes(virt_page_addr)) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() +} + +/// Enable the MMU and data + instruction caching. +/// +/// # Safety +/// +/// - Crucial function during kernel init. Changes the the complete memory view of the processor. +#[inline(always)] +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/mapping_record.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/mapping_record.rs new file mode 100644 index 000000000..0e0792201 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/mapping_record.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + +use super::{ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Type describing a virtual memory mapping. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +struct MappingRecordEntry { + pub users: [Option<&'static str>; 5], + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, + pub attribute_fields: AttributeFields, +} + +struct MappingRecord { + inner: [Option; 12], +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MAPPING_RECORD: InitStateLock = + InitStateLock::new(MappingRecord::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl MappingRecordEntry { + pub fn new( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Self { + Self { + users: [Some(name), None, None, None, None], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), + attribute_fields: *attr, + } + } + + fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { + if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { + return Ok(x); + }; + + Err("Storage for user info exhausted") + } + + pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { + let x = self.find_next_free_user()?; + *x = Some(user); + Ok(()) + } +} + +impl MappingRecord { + pub const fn new() -> Self { + Self { inner: [None; 12] } + } + + fn size(&self) -> usize { + self.inner.iter().filter(|x| x.is_some()).count() + } + + fn sort(&mut self) { + let upper_bound_exclusive = self.size(); + let entries = &mut self.inner[0..upper_bound_exclusive]; + + if !entries.is_sorted_by_key(|item| item.unwrap().virt_start_addr) { + entries.sort_unstable_by_key(|item| item.unwrap().virt_start_addr) + } + } + + fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { + if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { + return Ok(x); + } + + Err("Storage for mapping info exhausted") + } + + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() + .filter_map(|x| x.as_mut()) + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { + return false; + } + + if x.num_pages != phys_region.num_pages() { + return false; + } + + true + }) + } + + pub fn add( + &mut self, + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + let x = self.find_next_free()?; + + *x = Some(MappingRecordEntry::new( + name, + virt_region, + phys_region, + attr, + )); + + self.sort(); + + Ok(()) + } + + pub fn print(&self) { + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", + "Virtual", "Physical", "Size", "Attr", "Entity" + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + + for i in self.inner.iter().flatten() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match i.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if i.attribute_fields.execute_never { + "XN" + } else { + "X" + }; + + info!( + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, + phys_end_inclusive, + size, + unit, + attr, + acc_p, + xn, + i.users[0].unwrap() + ); + + for k in i.users[1..].iter() { + if let Some(additional_user) = *k { + info!( + " | {}", + additional_user + ); + } + } + } + + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +/// Add an entry to the mapping info record. +pub fn kernel_add( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) +} + +pub fn kernel_find_and_insert_mmio_duplicate( + mmio_descriptor: &MMIODescriptor, + new_user: &'static str, +) -> Option> { + let phys_region: MemoryRegion = (*mmio_descriptor).into(); + + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + + if let Err(x) = dup.add_user(new_user) { + warn!("{}", x); + } + + Some(dup.virt_start_addr) + }) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print() { + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/page_alloc.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/page_alloc.rs new file mode 100644 index 000000000..344afd200 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/page_alloc.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Page allocation. + +use super::MemoryRegion; +use crate::{ + memory::{AddressType, Virtual}, + synchronization::IRQSafeNullLock, + warn, +}; +use core::num::NonZeroUsize; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A page allocator that can be lazyily initialized. +pub struct PageAllocator { + pool: Option>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = + IRQSafeNullLock::new(PageAllocator::new()); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's MMIO virtual address allocator. +pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { + &KERNEL_MMIO_VA_ALLOCATOR +} + +impl PageAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { pool: None } + } + + /// Initialize the allocator. + pub fn init(&mut self, pool: MemoryRegion) { + if self.pool.is_some() { + warn!("Already initialized"); + return; + } + + self.pool = Some(pool); + } + + /// Allocate a number of pages. + pub fn alloc( + &mut self, + num_requested_pages: NonZeroUsize, + ) -> Result, &'static str> { + if self.pool.is_none() { + return Err("Allocator not initialized"); + } + + self.pool + .as_mut() + .unwrap() + .take_first_n_pages(num_requested_pages) + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..341ffc5c8 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +use super::{AttributeFields, MemoryRegion}; +use crate::memory::{Address, Physical, Virtual}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(target_arch = "aarch64")] +pub use arch_translation_table::FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Translation table interfaces. +pub mod interface { + use crate::memory::mmu::PageAddress; + + use super::*; + + /// Translation table operations. + pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self) -> Result<(), &'static str>; + + /// Map the given virtual memory region to the given physical memory region. + /// + /// # Safety + /// + /// - Using wrong attributes can cause multiple issues of different nature in the system. + /// - It is not required that the architectural implementation prevents aliasing. That is, + /// mapping to the same physical memory using multiple virtual addresses, which would + /// break Rust's ownership assumptions. This should be protected against in the kernel's + /// generic MMU code. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; + + /// Try to translate a virtual page address to a physical page address. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str>; + + /// Try to get the attributes of a page. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result; + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str>; + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use arch_translation_table::MinSizeTranslationTable; + use interface::TranslationTable; + use test_macros::kernel_test; + + /// Sanity checks for the TranslationTable implementation. + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. + let mut tables = MinSizeTranslationTable::new_for_runtime(); + + assert_eq!(tables.init(), Ok(())); + + let virt_end_exclusive_page_addr: PageAddress = PageAddress::MAX; + let virt_start_page_addr: PageAddress = + virt_end_exclusive_page_addr.checked_offset(-5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + + let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + + assert_eq!( + tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), + Ok(phys_start_page_addr) + ); + + assert_eq!( + tables.try_page_attributes(virt_start_page_addr.checked_offset(-1).unwrap()), + Err("Page marked invalid") + ); + + assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); + + let virt_addr = virt_start_page_addr.into_inner() + 0x100; + let phys_addr = phys_start_page_addr.into_inner() + 0x100; + assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs new file mode 100644 index 000000000..f6ac8d598 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs @@ -0,0 +1,378 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + +use crate::{ + bsp, common, + memory::{Address, AddressType, Physical}, +}; +use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct PageAddress { + inner: Address, +} + +/// A type that describes a region of memory in quantities of pages. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// An MMIO descriptor for use in device drivers. +#[derive(Copy, Clone)] +pub struct MMIODescriptor { + start_addr: Address, + end_addr_exclusive: Address, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------ +// PageAddress +//------------------------------------------------------------------------------ +impl PageAddress { + /// The largest value that can be represented by this type. + pub const MAX: Self = PageAddress { + inner: Address::new(usize::MAX).align_down_page(), + }; + + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + } + + /// Calculates the offset from the page address. + /// + /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * + /// page_size`. + pub fn checked_offset(self, count: isize) -> Option { + if count == 0 { + return Some(self); + } + + let delta = count + .unsigned_abs() + .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; + let result = if count.is_positive() { + self.inner.as_usize().checked_add(delta)? + } else { + self.inner.as_usize().checked_sub(delta)? + }; + + Some(Self { + inner: Address::new(result), + }) + } +} + +impl From for PageAddress { + fn from(addr: usize) -> Self { + assert!( + common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), + "Input usize not page aligned" + ); + + Self { + inner: Address::new(addr), + } + } +} + +impl From> for PageAddress { + fn from(addr: Address) -> Self { + assert!(addr.is_page_aligned(), "Input Address not page aligned"); + + Self { inner: addr } + } +} + +impl Step for PageAddress { + fn steps_between(start: &Self, end: &Self) -> Option { + if start > end { + return None; + } + + // Since start <= end, do unchecked arithmetic. + Some( + (end.inner.as_usize() - start.inner.as_usize()) + >> bsp::memory::mmu::KernelGranule::SHIFT, + ) + } + + fn forward_checked(start: Self, count: usize) -> Option { + start.checked_offset(count as isize) + } + + fn backward_checked(start: Self, count: usize) -> Option { + start.checked_offset(-(count as isize)) + } +} + +//------------------------------------------------------------------------------ +// MemoryRegion +//------------------------------------------------------------------------------ +impl MemoryRegion { + /// Create an instance. + pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { + assert!(start <= end_exclusive); + + Self { + start, + end_exclusive, + } + } + + fn as_range(&self) -> Range> { + self.into_iter() + } + + /// Returns the start page address. + pub fn start_page_addr(&self) -> PageAddress { + self.start + } + + /// Returns the start address. + pub fn start_addr(&self) -> Address { + self.start.into_inner() + } + + /// Returns the exclusive end page address. + pub fn end_exclusive_page_addr(&self) -> PageAddress { + self.end_exclusive + } + + /// Returns the exclusive end page address. + pub fn end_inclusive_page_addr(&self) -> PageAddress { + self.end_exclusive.checked_offset(-1).unwrap() + } + + /// Checks if self contains an address. + pub fn contains(&self, addr: Address) -> bool { + let page_addr = PageAddress::from(addr.align_down_page()); + self.as_range().contains(&page_addr) + } + + /// Checks if there is an overlap with another memory region. + pub fn overlaps(&self, other_region: &Self) -> bool { + let self_range = self.as_range(); + + self_range.contains(&other_region.start_page_addr()) + || self_range.contains(&other_region.end_inclusive_page_addr()) + } + + /// Returns the number of pages contained in this region. + pub fn num_pages(&self) -> usize { + PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() + } + + /// Returns the size in bytes of this region. + pub fn size(&self) -> usize { + // Invariant: start <= end_exclusive, so do unchecked arithmetic. + let end_exclusive = self.end_exclusive.into_inner().as_usize(); + let start = self.start.into_inner().as_usize(); + + end_exclusive - start + } + + /// Splits the MemoryRegion like: + /// + /// -------------------------------------------------------------------------------- + /// | | | | | | | | | | | | | | | | | | | + /// -------------------------------------------------------------------------------- + /// ^ ^ ^ + /// | | | + /// left_start left_end_exclusive | + /// | + /// ^ | + /// | | + /// right_start right_end_exclusive + /// + /// Left region is returned to the caller. Right region is the new region for this struct. + pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { + let count: usize = num_pages.into(); + + let left_end_exclusive = self.start.checked_offset(count as isize); + let left_end_exclusive = match left_end_exclusive { + None => return Err("Overflow while calculating left_end_exclusive"), + Some(x) => x, + }; + + if left_end_exclusive > self.end_exclusive { + return Err("Not enough free pages"); + } + + let allocation = Self { + start: self.start, + end_exclusive: left_end_exclusive, + }; + self.start = left_end_exclusive; + + Ok(allocation) + } +} + +impl IntoIterator for MemoryRegion { + type Item = PageAddress; + type IntoIter = Range; + + fn into_iter(self) -> Self::IntoIter { + Range { + start: self.start, + end: self.end_exclusive, + } + } +} + +impl From for MemoryRegion { + fn from(desc: MMIODescriptor) -> Self { + let start = PageAddress::from(desc.start_addr.align_down_page()); + let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); + + Self { + start, + end_exclusive, + } + } +} + +//------------------------------------------------------------------------------ +// MMIODescriptor +//------------------------------------------------------------------------------ + +impl MMIODescriptor { + /// Create an instance. + pub const fn new(start_addr: Address, size: usize) -> Self { + assert!(size > 0); + let end_addr_exclusive = Address::new(start_addr.as_usize() + size); + + Self { + start_addr, + end_addr_exclusive, + } + } + + /// Return the start address. + pub const fn start_addr(&self) -> Address { + self.start_addr + } + + /// Return the exclusive end address. + pub fn end_addr_exclusive(&self) -> Address { + self.end_addr_exclusive + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::Virtual; + use test_macros::kernel_test; + + /// Sanity of [PageAddress] methods. + #[kernel_test] + fn pageaddress_type_method_sanity() { + let page_addr: PageAddress = + PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); + + assert_eq!( + page_addr.checked_offset(-2), + Some(PageAddress::::from(0)) + ); + + assert_eq!( + page_addr.checked_offset(2), + Some(PageAddress::::from( + bsp::memory::mmu::KernelGranule::SIZE * 4 + )) + ); + + assert_eq!( + PageAddress::::from(0).checked_offset(0), + Some(PageAddress::::from(0)) + ); + assert_eq!(PageAddress::::from(0).checked_offset(-1), None); + + let max_page_addr = Address::::new(usize::MAX).align_down_page(); + assert_eq!( + PageAddress::::from(max_page_addr).checked_offset(1), + None + ); + + let zero = PageAddress::::from(0); + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); + } + + /// Sanity of [MemoryRegion] methods. + #[kernel_test] + fn memoryregion_type_method_sanity() { + let zero = PageAddress::::from(0); + let zero_region = MemoryRegion::new(zero, zero); + assert_eq!(zero_region.num_pages(), 0); + assert_eq!(zero_region.size(), 0); + + let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); + let one_region = MemoryRegion::new(zero, one); + assert_eq!(one_region.num_pages(), 1); + assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); + + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + let mut three_region = MemoryRegion::new(zero, three); + assert!(three_region.contains(zero.into_inner())); + assert!(!three_region.contains(three.into_inner())); + assert!(three_region.overlaps(&one_region)); + + let allocation = three_region + .take_first_n_pages(NonZeroUsize::new(2).unwrap()) + .unwrap(); + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + + for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE + ); + } + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/panic_wait.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/panic_wait.rs new file mode 100644 index 000000000..c6f3a9c7b --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/panic_wait.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, exception, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + _panic_exit() +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/print.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/state.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/state.rs new file mode 100644 index 000000000..6d99beedb --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/synchronization.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/synchronization.rs new file mode 100644 index 000000000..5740b63e5 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/synchronization.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use crate::{exception, state}; + +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/src/time.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rb b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..682ea9b8a --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, memory, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/01_timer_sanity.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..1581a02e0 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, memory, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..09d177981 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + info!("Writing to bottom of address space to address 1 GiB..."); + let big_addr: u64 = 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rb b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..1a3029112 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/04_exception_irq_sanity.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/04_exception_irq_sanity.rs new file mode 100644 index 000000000..fcace8979 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception, memory}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + memory::init(); + bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/boot_test_string.rb b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/panic_exit_success/mod.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/16_virtual_mem_part4_higher_half_kernel/kernel/tests/panic_wait_forever/mod.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/Cargo.toml b/16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/src/lib.rs b/16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/16_virtual_mem_part4_higher_half_kernel/libraries/test-types/Cargo.toml b/16_virtual_mem_part4_higher_half_kernel/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/16_virtual_mem_part4_higher_half_kernel/libraries/test-types/src/lib.rs b/16_virtual_mem_part4_higher_half_kernel/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb new file mode 100644 index 000000000..053cac194 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb @@ -0,0 +1,314 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Bitfield manipulation. +class BitField + def initialize + @value = 0 + end + + def self.attr_bitfield(name, offset, num_bits) + define_method("#{name}=") do |bits| + mask = (2**num_bits) - 1 + + raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? + + # Clear bitfield + @value &= ~(mask << offset) + + # Set it + @value |= (bits << offset) + end + end + + def to_i + @value + end + + def size_in_byte + 8 + end +end + +# An array class that knows its memory location. +class CArray < Array + attr_reader :phys_start_addr + + def initialize(phys_start_addr, size, &block) + @phys_start_addr = phys_start_addr + + super(size, &block) + end + + def size_in_byte + inject(0) { |sum, n| sum + n.size_in_byte } + end +end + +#--------------------------------------------------------------------------------------------------- +# Arch:: +#--------------------------------------------------------------------------------------------------- +module Arch +#--------------------------------------------------------------------------------------------------- +# Arch::ARMv8 +#--------------------------------------------------------------------------------------------------- +module ARMv8 +# ARMv8 Table Descriptor. +class Stage1TableDescriptor < BitField + module NextLevelTableAddr + OFFSET = 16 + NUMBITS = 32 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + BLOCK = 0 + TABLE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def next_level_table_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__next_level_table_addr = addr + end + + private :__next_level_table_addr= +end + +# ARMv8 level 3 page descriptor. +class Stage1PageDescriptor < BitField + module UXN + OFFSET = 54 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module PXN + OFFSET = 53 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module OutputAddr + OFFSET = 16 + NUMBITS = 32 + end + + module AF + OFFSET = 10 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module SH + OFFSET = 8 + NUMBITS = 2 + + INNER_SHAREABLE = 0b11 + end + + module AP + OFFSET = 6 + NUMBITS = 2 + + RW_EL1 = 0b00 + RO_EL1 = 0b10 + end + + module AttrIndx + OFFSET = 2 + NUMBITS = 3 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + RESERVED_INVALID = 0 + PAGE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) + attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) + attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) + attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) + attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) + attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) + attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def output_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__output_addr = addr + end + + private :__output_addr= +end + +# Translation table representing the structure defined in translation_table.rs. +class TranslationTable + module MAIR + NORMAL = 1 + end + + def initialize + do_sanity_checks + + num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT + + @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) + + @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte + @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) + + populate_lvl2_entries + end + + def map_at(virt_region, phys_region, attributes) + return if virt_region.empty? + + raise if virt_region.size != phys_region.size + raise if phys_region.last > BSP.phys_addr_space_end_page + + virt_region.zip(phys_region).each do |virt_page, phys_page| + desc = page_descriptor_from(virt_page) + set_lvl3_entry(desc, phys_page, attributes) + end + end + + def to_binary + data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) + data.pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr_binary + [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr + @lvl2_phys_start_addr + end + + private + + def do_sanity_checks + raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE + raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? + end + + def new_lvl3(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + temp = CArray.new(start_addr, 8192) do + Stage1PageDescriptor.new + end + start_addr += temp.size_in_byte + + temp + end + end + + def new_lvl2(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + Stage1TableDescriptor.new + end + end + + def populate_lvl2_entries + @lvl2.each_with_index do |descriptor, i| + descriptor.next_level_table_addr = @lvl3[i].phys_start_addr + descriptor.type = Stage1TableDescriptor::Type::TABLE + descriptor.valid = Stage1TableDescriptor::Valid::TRUE + end + end + + def lvl2_lvl3_index_from(addr) + addr -= BSP.kernel_virt_start_addr + + lvl2_index = addr >> Granule512MiB::SHIFT + lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT + + raise unless lvl2_index < @lvl2.size + + [lvl2_index, lvl3_index] + end + + def page_descriptor_from(virt_addr) + lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) + + @lvl3[lvl2_index][lvl3_index] + end + + # rubocop:disable Metrics/MethodLength + def set_attributes(desc, attributes) + case attributes.mem_attributes + when :CacheableDRAM + desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE + desc.attr_indx = MAIR::NORMAL + else + raise 'Invalid input' + end + + desc.ap = case attributes.acc_perms + when :ReadOnly + Stage1PageDescriptor::AP::RO_EL1 + when :ReadWrite + Stage1PageDescriptor::AP::RW_EL1 + else + raise 'Invalid input' + + end + + desc.pxn = if attributes.execute_never + Stage1PageDescriptor::PXN::TRUE + else + Stage1PageDescriptor::PXN::FALSE + end + + desc.uxn = Stage1PageDescriptor::UXN::TRUE + end + # rubocop:enable Metrics/MethodLength + + def set_lvl3_entry(desc, output_addr, attributes) + desc.output_addr = output_addr + desc.af = Stage1PageDescriptor::AF::TRUE + desc.type = Stage1PageDescriptor::Type::PAGE + desc.valid = Stage1PageDescriptor::Valid::TRUE + + set_attributes(desc, attributes) + end +end +end +end diff --git a/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb new file mode 100644 index 000000000..93bcedd94 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Raspberry Pi 3 + 4 +class RaspberryPi + attr_reader :kernel_granule, :kernel_virt_addr_space_size, :kernel_virt_start_addr + + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + + def initialize + @kernel_granule = Granule64KiB + + @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') + @kernel_virt_start_addr = KERNEL_ELF.symbol_value('__kernel_virt_start_addr') + + @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') + @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( + 'PHYS_KERNEL_TABLES_BASE_ADDR' + ) + end + + def phys_addr_of_kernel_tables + KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) + end + + def kernel_tables_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) + end + + def phys_kernel_tables_base_addr_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) + end + + def phys_addr_space_end_page + x = MEMORY_SRC.grep(/pub const END/) + x = case BSP_TYPE + when :rpi3 + x[0] + when :rpi4 + x[1] + else + raise + end + + x.scan(/\d+/).join.to_i(16) + end +end diff --git a/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/generic.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/generic.rb new file mode 100644 index 000000000..743840e00 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/generic.rb @@ -0,0 +1,179 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +module Granule64KiB + SIZE = 64 * 1024 + SHIFT = Math.log2(SIZE).to_i +end + +module Granule512MiB + SIZE = 512 * 1024 * 1024 + SHIFT = Math.log2(SIZE).to_i + MASK = SIZE - 1 +end + +# Monkey-patch Integer with some helper functions. +class Integer + def power_of_two? + self[0].zero? + end + + def aligned?(alignment) + raise unless alignment.power_of_two? + + (self & (alignment - 1)).zero? + end + + def align_up(alignment) + raise unless alignment.power_of_two? + + (self + alignment - 1) & ~(alignment - 1) + end + + def to_hex_underscore(with_leading_zeros: false) + fmt = with_leading_zeros ? '%016x' : '%x' + value = format(fmt, self).to_s.reverse.scan(/.{4}|.+/).join('_').reverse + + format('0x%s', value) + end +end + +# An array where each value is the start address of a Page. +class MemoryRegion < Array + def initialize(start_addr, size, granule_size) + raise unless start_addr.aligned?(granule_size) + raise unless size.positive? + raise unless (size % granule_size).zero? + + num_pages = size / granule_size + super(num_pages) do |i| + (i * granule_size) + start_addr + end + end +end + +# Collection of memory attributes. +class AttributeFields + attr_reader :mem_attributes, :acc_perms, :execute_never + + def initialize(mem_attributes, acc_perms, execute_never) + @mem_attributes = mem_attributes + @acc_perms = acc_perms + @execute_never = execute_never + end + + def to_s + x = case @mem_attributes + when :CacheableDRAM + 'C' + else + '?' + end + + y = case @acc_perms + when :ReadWrite + 'RW' + when :ReadOnly + 'RO' + else + '??' + end + + z = @execute_never ? 'XN' : 'X ' + + "#{x} #{y} #{z}" + end +end + +# A container that describes a virt-to-phys region mapping. +class MappingDescriptor + @max_section_name_length = 'Sections'.length + + class << self + attr_accessor :max_section_name_length + + def update_max_section_name_length(length) + @max_section_name_length = [@max_section_name_length, length].max + end + end + + attr_reader :name, :virt_region, :phys_region, :attributes + + def initialize(name, virt_region, phys_region, attributes) + @name = name + @virt_region = virt_region + @phys_region = phys_region + @attributes = attributes + end + + def to_s + name = @name.ljust(self.class.max_section_name_length) + virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) + phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) + size = ((@virt_region.size * 65_536) / 1024).to_s.rjust(3) + + "#{name} | #{virt_start} | #{phys_start} | #{size} KiB | #{@attributes}" + end + + def self.print_divider + print ' ' + print '-' * max_section_name_length + puts '--------------------------------------------------------------------' + end + + def self.print_header + print_divider + print ' ' + print 'Sections'.center(max_section_name_length) + print ' ' + print 'Virt Start Addr'.center(21) + print ' ' + print 'Phys Start Addr'.center(21) + print ' ' + print 'Size'.center(7) + print ' ' + print 'Attr'.center(7) + puts + print_divider + end +end + +def kernel_map_binary + mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors + + # Generate_mapping_descriptors updates the header being printed with this call. So it must come + # afterwards. + MappingDescriptor.print_header + + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' + puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end + + MappingDescriptor.print_divider +end + +def kernel_patch_tables(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel table struct at ELF file offset ' + puts BSP.kernel_tables_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.to_binary, BSP.kernel_tables_offset_in_file) +end + +def kernel_patch_base_addr(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel tables physical base address start argument to value ' + print TRANSLATION_TABLES.phys_tables_base_addr.to_hex_underscore + print ' at ELF file offset ' + puts BSP.phys_kernel_tables_base_addr_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.phys_tables_base_addr_binary, + BSP.phys_kernel_tables_base_addr_offset_in_file) +end diff --git a/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/kernel_elf.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/kernel_elf.rb new file mode 100644 index 000000000..5ba78d9df --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/kernel_elf.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + SECTION_FLAG_ALLOC = 2 + + def initialize(kernel_elf_path) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + end + + def machine + @elf.machine.to_sym + end + + def symbol_value(symbol_name) + @symtab_section.symbol_by_name(symbol_name).header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_to_phys(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + translation_offset = segment.header.p_vaddr - segment.header.p_paddr + + virt_addr - translation_offset + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + def sections_in_segment(segment) + head = segment.mem_head + tail = segment.mem_tail + + sections = @elf.each_sections.select do |section| + file_offset = section.header.sh_addr + flags = section.header.sh_flags + + file_offset >= head && file_offset < tail && (flags & SECTION_FLAG_ALLOC != 0) + end + + sections.map(&:name).join(' ') + end + + def select_load_segments + @elf.each_segments.select do |segment| + segment.instance_of?(ELFTools::Segments::LoadSegment) + end + end + + def segment_get_acc_perms(segment) + if segment.readable? && segment.writable? + :ReadWrite + elsif segment.readable? + :ReadOnly + else + :Invalid + end + end + + def update_max_section_name_length(descriptors) + MappingDescriptor.update_max_section_name_length(descriptors.map { |i| i.name.size }.max) + end + + def generate_mapping_descriptors + descriptors = select_load_segments.map do |segment| + # Assume each segment is page aligned. + size = segment.mem_size.align_up(BSP.kernel_granule::SIZE) + virt_start_addr = segment.header.p_vaddr + phys_start_addr = segment.header.p_paddr + acc_perms = segment_get_acc_perms(segment) + execute_never = !segment.executable? + section_names = sections_in_segment(segment) + + virt_region = MemoryRegion.new(virt_start_addr, size, BSP.kernel_granule::SIZE) + phys_region = MemoryRegion.new(phys_start_addr, size, BSP.kernel_granule::SIZE) + attributes = AttributeFields.new(:CacheableDRAM, acc_perms, execute_never) + + MappingDescriptor.new(section_names, virt_region, phys_region, attributes) + end + + update_max_section_name_length(descriptors) + descriptors + end +end diff --git a/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/main.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/main.rb new file mode 100755 index 000000000..22ab24fd5 --- /dev/null +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/main.rb @@ -0,0 +1,46 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'generic' +require_relative 'kernel_elf' +require_relative 'bsp' +require_relative 'arch' + +BSP_TYPE = ARGV[0].to_sym +kernel_elf_path = ARGV[1] + +start = Time.now + +KERNEL_ELF = KernelELF.new(kernel_elf_path) + +BSP = case BSP_TYPE + when :rpi3, :rpi4 + RaspberryPi.new + else + raise + end + +TRANSLATION_TABLES = case KERNEL_ELF.machine + when :AArch64 + Arch::ARMv8::TranslationTable.new + else + raise + end + +kernel_map_binary +kernel_patch_tables(kernel_elf_path) +kernel_patch_base_addr(kernel_elf_path) + +elapsed = Time.now - start + +print 'Finished'.rjust(12).green.bold +puts " in #{elapsed.round(2)}s" diff --git a/17_kernel_symbols/.cargo/config.toml b/17_kernel_symbols/.cargo/config.toml new file mode 100644 index 000000000..e34764853 --- /dev/null +++ b/17_kernel_symbols/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.'cfg(target_os = "none")'] +runner = "target/kernel_test_runner.sh" diff --git a/17_kernel_symbols/.vscode/settings.json b/17_kernel_symbols/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/17_kernel_symbols/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/17_kernel_symbols/Cargo.lock b/17_kernel_symbols/Cargo.lock new file mode 100644 index 000000000..382a3bda5 --- /dev/null +++ b/17_kernel_symbols/Cargo.lock @@ -0,0 +1,96 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "debug-symbol-types" +version = "0.1.0" + +[[package]] +name = "kernel_symbols" +version = "0.1.0" +dependencies = [ + "debug-symbol-types", +] + +[[package]] +name = "mingo" +version = "0.17.0" +dependencies = [ + "aarch64-cpu", + "debug-symbol-types", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/17_kernel_symbols/Cargo.toml b/17_kernel_symbols/Cargo.toml new file mode 100644 index 000000000..1ea72c9f0 --- /dev/null +++ b/17_kernel_symbols/Cargo.toml @@ -0,0 +1,10 @@ +[workspace] + +members = [ + "libraries/*", + "kernel", + "kernel_symbols" +] + +[profile.release] +lto = true diff --git a/17_kernel_symbols/Makefile b/17_kernel_symbols/Makefile new file mode 100644 index 000000000..3c33cd66a --- /dev/null +++ b/17_kernel_symbols/Makefile @@ -0,0 +1,387 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF_RAW = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_RAW_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Translation tables +##------------------------------------------------------------------------------ +TT_TOOL_PATH = tools/translation_table_tool + +KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables +KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) + +##------------------------------------------------------------------------------ +## Kernel symbols +##------------------------------------------------------------------------------ +export KERNEL_SYMBOLS_TOOL_PATH = tools/kernel_symbols_tool + +KERNEL_ELF_TTABLES_SYMS = target/$(TARGET)/release/kernel+ttables+symbols + +# Unlike with KERNEL_ELF_RAW, we are not relying on dep-info here. One of the reasons being that the +# name of the generated symbols file varies between runs, which can cause confusion. +KERNEL_ELF_TTABLES_SYMS_DEPS = $(KERNEL_ELF_TTABLES) \ + $(wildcard kernel_symbols/*) \ + $(wildcard $(KERNEL_SYMBOLS_TOOL_PATH)/*) + +export TARGET +export KERNEL_SYMBOLS_INPUT_ELF = $(KERNEL_ELF_TTABLES) +export KERNEL_SYMBOLS_OUTPUT_ELF = $(KERNEL_ELF_TTABLES_SYMS) + +KERNEL_ELF = $(KERNEL_ELF_TTABLES_SYMS) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Precompute the kernel translation tables and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) + $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") + @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) + +##------------------------------------------------------------------------------ +## Generate kernel symbols and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES_SYMS): $(KERNEL_ELF_TTABLES_SYMS_DEPS) + $(call color_header, "Generating kernel symbols and patching kernel ELF") + @$(MAKE) --no-print-directory -f kernel_symbols.mk + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF_TTABLES_SYMS) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES_SYMS) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: clean + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_ELF_SYMS="$${TEST_ELF}_syms" + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null + + # This overrides the two ENV variables. The other ENV variables that are required as input for + # the .mk file are set already because they are exported by this Makefile and this script is + # started by the same. + KERNEL_SYMBOLS_INPUT_ELF=$$TEST_ELF \ + KERNEL_SYMBOLS_OUTPUT_ELF=$$TEST_ELF_SYMS \ + $(MAKE) --no-print-directory -f kernel_symbols.mk > /dev/null 2>&1 + + $(OBJCOPY_CMD) $$TEST_ELF_SYMS $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/17_kernel_symbols/README.md b/17_kernel_symbols/README.md new file mode 100644 index 000000000..78962bd80 --- /dev/null +++ b/17_kernel_symbols/README.md @@ -0,0 +1,959 @@ +# Tutorial 17 - Kernel Symbols + +## tl;dr + +- To enrich and augment existing and future debugging code, we add support for `kernel symbol` + lookup. + +## Table of Contents + +- [Introduction](#introduction) +- [Implementation](#implementation) + - [Linking Changes](#linking-changes) + - [Kernel Symbols Tool](#kernel-symbols-tool) + - [Lookup Code](#lookup-code) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +Ever since the first tutorial, it was possible to execute the `make nm` target in order to view all +`kernel symbols`. The kernel itself, however, does not have any means yet to correlate a virtual +address to a symbol during runtime. Gaining this capability would be useful for augmenting +debug-related prints. For example, when the kernel is handling an `exception`, it prints the content +of the `exception link register`, which is the program address where the CPU was executing from when +the exception happened. + +Until now, in order to understand to which function or code such an address belongs to, a manual +lookup by the person debugging the issue was necessary. In this tutorial, we are adding a `data +structure` to the kernel which contains _all the symbol names and corresponding address ranges_. +This enables the kernel to print symbol names in existing and future debug-related code, which +improves triaging of issues by humans, because it does away with the manual lookup. + +This tutorial is mostly is an enabler for the upcoming tutorial that will add [`backtracing`] +support. + +[`backtracing`]: https://en.wikipedia.org/wiki/Stack_trace + +## Implementation + +First of all, a new support crate is added under `$ROOT/libraries/debug-symbol-types`. It contains +the definition for `struct Symbol`: + +```rust +/// A symbol containing a size. +#[repr(C)] +pub struct Symbol { + addr_range: Range, + name: &'static str, +} +``` + +To enable the kernel to lookup symbol names, we will add an `array` to the kernel binary that +contains all the kernel symbols. Because we can query the final symbol names and addresses only +_after_ the kernel has been `linked`, the same approach as for the `translation tables` will be +used: The symbols array will be patched into a `placeholder section` of the final kernel `ELF`. + +### Linking Changes + +In the `kernel.ld` linker script, we define a new section named `kernel_symbols` and give it a size +of `32 KiB`: + +```ld.s + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + .got : ALIGN(8) { *(.got) } :segment_code + .kernel_symbols : ALIGN(8) { + __kernel_symbols_start = .; + . += 32 * 1024; + } :segment_code +``` + +Also, we are providing the start address of the section through the symbol `__kernel_symbols_start`, +which will be used by our `Rust` code later on. + +### Kernel Symbols Tool + +Under `$ROOT/tools/kernel_symbols_tool`, we are adding a helper tool that is able to dynamically +generate an `array` of all the kernel symbols and patch it into the final kernel `ELF`. In our main +`Makefile`, we are invoking the tool after the translation table generation. In the first step, the +tool generates a temporary `Rust` file that instantiates the symbols array. Here is an example of +how this can look like: + +```console +$ head ./target/aarch64-unknown-none-softfloat/release/kernel+ttables_symbols_demangled.rs +``` +```rust +use debug_symbol_types::Symbol; + +# [no_mangle] +# [link_section = ".rodata.symbol_desc"] +static KERNEL_SYMBOLS: [Symbol; 139] = [ + Symbol::new(18446744072635809792, 124, "_start"), + Symbol::new(18446744072635809920, 8, "BOOT_CORE_ID"), + Symbol::new(18446744072635809928, 8, "PHYS_KERNEL_TABLES_BASE_ADDR"), + Symbol::new(18446744072635809936, 80, "_start_rust"), + Symbol::new(18446744072635813888, 84, "__exception_restore_context"), + // Many more +``` + +Next, the _helper crate_ `$ROOT/kernel_symbols` is compiled. This crate contains a single `main.rs` +that just includes the temporary symbols file shown above. + +```rust +//! Generation of kernel symbols. + +#![no_std] +#![no_main] + +#[cfg(feature = "generated_symbols_available")] +include!(env!("KERNEL_SYMBOLS_DEMANGLED_RS")); +``` + +`KERNEL_SYMBOLS_DEMANGLED_RS` is set by the corresponding `build.rs` file. The helper crate has its +own `linker file`, which ensures that that just the array and the corresponding strings that it +references are kept: + +```ld.s +SECTIONS +{ + .rodata : { + ASSERT(. > 0xffffffff00000000, "Expected higher half address") + + KEEP(*(.rodata.symbol_desc*)) + . = ALIGN(8); + *(.rodata*) + } +} +``` + +Afterwards, `objcopy` is used to strip the produced helper crate ELF. What remains is a small +`binary blob` that just contains the symbols array and the `names` that are referenced. To ensure +that these references are valid kernel addresses (remember that those are defined as `name: &'static +str`, so basically a pointer to a kernel address), the sub-makefile compiling this helper crate +(`$ROOT/kernel_symbols.mk`) did the following: + +It used the `kernel_symbols_tool` to query the virtual address of the `kernel_symbols` **section** +(of the final kernel ELF). This address was then supplied to the linker when the helper crate was +linked (emphasis on the `--section-start=.rodata=` part): + +```Makefile +GET_SYMBOLS_SECTION_VIRT_ADDR = $(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) \ + --get_symbols_section_virt_addr $(KERNEL_SYMBOLS_OUTPUT_ELF) + +RUSTFLAGS = -C link-arg=--script=$(KERNEL_SYMBOLS_LINKER_SCRIPT) \ + -C link-arg=--section-start=.rodata=$$($(GET_SYMBOLS_SECTION_VIRT_ADDR)) +``` + +This might be a bit convoluted, but the main take away is: This ensures that the start address of +the `.rodata` section of the `kernel_symbols` helper crate is exactly the same address as the +`placeholder section` of the final kernel ELF where the symbols `binary blob` will be patched into. +The latter is the last step done by the tool. + +### Lookup Code + +In the kernel, we add the file `src/symbols.rs`. It makes the linker-provided symbol +`__kernel_symbols_start` that we saw earlier accesible, and also defines `NUM_KERNEL_SYMBOLS`: + +```rust +#[no_mangle] +static NUM_KERNEL_SYMBOLS: u64 = 0; +``` + +When the `kernel_symbols_tool` patches the symbols blob into the kernel ELF, it also updates this +value to reflect the number of symbols that are available. This is needed for the code that +internally crafts the slice of symbols that the kernel uses for lookup: + +```rust +fn kernel_symbol_section_virt_start_addr() -> Address { + Address::new(unsafe { __kernel_symbols_start.get() as usize }) +} + +fn num_kernel_symbols() -> usize { + unsafe { + // Read volatile is needed here to prevent the compiler from optimizing NUM_KERNEL_SYMBOLS + // away. + core::ptr::read_volatile(&NUM_KERNEL_SYMBOLS as *const u64) as usize + } +} + +fn kernel_symbols_slice() -> &'static [Symbol] { + let ptr = kernel_symbol_section_virt_start_addr().as_usize() as *const Symbol; + + unsafe { slice::from_raw_parts(ptr, num_kernel_symbols()) } +} +``` + +Lookup is done by just iterating over the slice: + +```rust +/// Retrieve the symbol corresponding to a virtual address, if any. +pub fn lookup_symbol(addr: Address) -> Option<&'static Symbol> { + kernel_symbols_slice() + .iter() + .find(|&i| i.contains(addr.as_usize())) +} +``` + +And that's it for this tutorial. The upcoming tutorial on `backtracing` will put this code to more +prominent use. + +## Test it + +For now, symbol lookup can be observed in the integration test for synchronous exception handling. +Here, the kernel now also prints the symbol name that corresponds to the value of `ELR_EL1`. In the +following case, this is `kernel_init()`, which is where the the exception is generated in the test: + +```console +$ TEST=02_exception_sync_page_fault make test_integration +[...] + ------------------------------------------------------------------- + 🦀 Testing synchronous exception handling by causing a page fault + ------------------------------------------------------------------- + + [ 0.002640] Writing to bottom of address space to address 1 GiB... + [ 0.004549] Kernel panic! + + Panic location: + File 'kernel/src/_arch/aarch64/exception.rs', line 59, column 5 + + CPU Exception! + + ESR_EL1: 0x96000004 + + ... + + ELR_EL1: 0xffffffffc0001118 + Symbol: kernel_init +``` + +## Diff to previous +```diff + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/Cargo.toml 17_kernel_symbols/Cargo.toml +--- 16_virtual_mem_part4_higher_half_kernel/Cargo.toml ++++ 17_kernel_symbols/Cargo.toml +@@ -2,7 +2,8 @@ + + members = [ + "libraries/*", +- "kernel" ++ "kernel", ++ "kernel_symbols" + ] + + [profile.release] + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml 17_kernel_symbols/kernel/Cargo.toml +--- 16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml ++++ 17_kernel_symbols/kernel/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.16.0" ++version = "0.17.0" + authors = ["Andre Richter "] + edition = "2021" + +@@ -16,6 +16,7 @@ + + [dependencies] + test-types = { path = "../libraries/test-types" } ++debug-symbol-types = { path = "../libraries/debug-symbol-types" } + + # Optional dependencies + tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.rs 17_kernel_symbols/kernel/src/_arch/aarch64/exception.rs +--- 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.rs ++++ 17_kernel_symbols/kernel/src/_arch/aarch64/exception.rs +@@ -11,7 +11,7 @@ + //! + //! crate::exception::arch_exception + +-use crate::exception; ++use crate::{exception, memory, symbols}; + use aarch64_cpu::{asm::barrier, registers::*}; + use core::{arch::global_asm, cell::UnsafeCell, fmt}; + use tock_registers::{ +@@ -260,6 +260,14 @@ + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; ++ writeln!( ++ f, ++ " Symbol: {}", ++ match symbols::lookup_symbol(memory::Address::new(self.elr_el1 as usize)) { ++ Some(sym) => sym.name(), ++ _ => "Symbol not found", ++ } ++ )?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld 17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel.ld +--- 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld ++++ 17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel.ld +@@ -56,7 +56,11 @@ + *(.text*) /* Everything else */ + } :segment_code + +- .rodata : ALIGN(8) { *(.rodata*) } :segment_code ++ .rodata : ALIGN(8) { *(.rodata*) } :segment_code ++ .kernel_symbols : ALIGN(8) { ++ __kernel_symbols_start = .; ++ . += 32 * 1024; ++ } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs 17_kernel_symbols/kernel/src/bsp/raspberrypi/memory.rs +--- 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs ++++ 17_kernel_symbols/kernel/src/bsp/raspberrypi/memory.rs +@@ -20,6 +20,7 @@ + //! | .text | + //! | .rodata | + //! | .got | ++//! | .kernel_symbols | + //! | | + //! +---------------------------------------+ + //! | | data_start == code_end_exclusive +@@ -41,6 +42,7 @@ + //! | .text | + //! | .rodata | + //! | .got | ++//! | .kernel_symbols | + //! | | + //! +---------------------------------------+ + //! | | data_start == code_end_exclusive + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs 17_kernel_symbols/kernel/src/lib.rs +--- 16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs ++++ 17_kernel_symbols/kernel/src/lib.rs +@@ -142,6 +142,7 @@ + pub mod memory; + pub mod print; + pub mod state; ++pub mod symbols; + pub mod time; + + //-------------------------------------------------------------------------------------------------- + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel/src/symbols.rs 17_kernel_symbols/kernel/src/symbols.rs +--- 16_virtual_mem_part4_higher_half_kernel/kernel/src/symbols.rs ++++ 17_kernel_symbols/kernel/src/symbols.rs +@@ -0,0 +1,88 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Debug symbol support. ++ ++use crate::memory::{Address, Virtual}; ++use core::{cell::UnsafeCell, slice}; ++use debug_symbol_types::Symbol; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++// Symbol from the linker script. ++extern "Rust" { ++ static __kernel_symbols_start: UnsafeCell<()>; ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++/// This will be patched to the correct value by the "kernel symbols tool" after linking. This given ++/// value here is just a (safe) dummy. ++#[no_mangle] ++static NUM_KERNEL_SYMBOLS: u64 = 0; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++fn kernel_symbol_section_virt_start_addr() -> Address { ++ Address::new(unsafe { __kernel_symbols_start.get() as usize }) ++} ++ ++fn num_kernel_symbols() -> usize { ++ unsafe { ++ // Read volatile is needed here to prevent the compiler from optimizing NUM_KERNEL_SYMBOLS ++ // away. ++ core::ptr::read_volatile(&NUM_KERNEL_SYMBOLS as *const u64) as usize ++ } ++} ++ ++fn kernel_symbols_slice() -> &'static [Symbol] { ++ let ptr = kernel_symbol_section_virt_start_addr().as_usize() as *const Symbol; ++ ++ unsafe { slice::from_raw_parts(ptr, num_kernel_symbols()) } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Retrieve the symbol corresponding to a virtual address, if any. ++pub fn lookup_symbol(addr: Address) -> Option<&'static Symbol> { ++ kernel_symbols_slice() ++ .iter() ++ .find(|&i| i.contains(addr.as_usize())) ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Testing ++//-------------------------------------------------------------------------------------------------- ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ use test_macros::kernel_test; ++ ++ /// Sanity of symbols module. ++ #[kernel_test] ++ fn symbols_sanity() { ++ let first_sym = lookup_symbol(Address::new( ++ crate::common::is_aligned as *const usize as usize, ++ )) ++ .unwrap() ++ .name(); ++ ++ assert_eq!(first_sym, "libkernel::common::is_aligned"); ++ ++ let second_sym = lookup_symbol(Address::new(crate::version as *const usize as usize)) ++ .unwrap() ++ .name(); ++ ++ assert_eq!(second_sym, "libkernel::version"); ++ } ++} + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel_symbols/build.rs 17_kernel_symbols/kernel_symbols/build.rs +--- 16_virtual_mem_part4_higher_half_kernel/kernel_symbols/build.rs ++++ 17_kernel_symbols/kernel_symbols/build.rs +@@ -0,0 +1,14 @@ ++use std::{env, path::Path}; ++ ++fn main() { ++ if let Ok(path) = env::var("KERNEL_SYMBOLS_DEMANGLED_RS") { ++ if Path::new(&path).exists() { ++ println!("cargo:rustc-cfg=feature=\"generated_symbols_available\"") ++ } ++ } ++ ++ println!( ++ "cargo:rerun-if-changed={}", ++ Path::new("kernel_symbols.ld").display() ++ ); ++} + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel_symbols/Cargo.toml 17_kernel_symbols/kernel_symbols/Cargo.toml +--- 16_virtual_mem_part4_higher_half_kernel/kernel_symbols/Cargo.toml ++++ 17_kernel_symbols/kernel_symbols/Cargo.toml +@@ -0,0 +1,15 @@ ++[package] ++name = "kernel_symbols" ++version = "0.1.0" ++edition = "2021" ++ ++[features] ++default = [] ++generated_symbols_available = [] ++ ++##-------------------------------------------------------------------------------------------------- ++## Dependencies ++##-------------------------------------------------------------------------------------------------- ++ ++[dependencies] ++debug-symbol-types = { path = "../libraries/debug-symbol-types" } + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel_symbols/kernel_symbols.ld 17_kernel_symbols/kernel_symbols/kernel_symbols.ld +--- 16_virtual_mem_part4_higher_half_kernel/kernel_symbols/kernel_symbols.ld ++++ 17_kernel_symbols/kernel_symbols/kernel_symbols.ld +@@ -0,0 +1,15 @@ ++/* SPDX-License-Identifier: MIT OR Apache-2.0 ++ * ++ * Copyright (c) 2022-2023 Andre Richter ++ */ ++ ++SECTIONS ++{ ++ .rodata : { ++ ASSERT(. > 0xffffffff00000000, "Expected higher half address") ++ ++ KEEP(*(.rodata.symbol_desc*)) ++ . = ALIGN(8); ++ *(.rodata*) ++ } ++} + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel_symbols/src/main.rs 17_kernel_symbols/kernel_symbols/src/main.rs +--- 16_virtual_mem_part4_higher_half_kernel/kernel_symbols/src/main.rs ++++ 17_kernel_symbols/kernel_symbols/src/main.rs +@@ -0,0 +1,16 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Generation of kernel symbols. ++ ++#![no_std] ++#![no_main] ++ ++#[cfg(feature = "generated_symbols_available")] ++include!(env!("KERNEL_SYMBOLS_DEMANGLED_RS")); ++ ++#[panic_handler] ++fn panic(_info: &core::panic::PanicInfo) -> ! { ++ unimplemented!() ++} + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/kernel_symbols.mk 17_kernel_symbols/kernel_symbols.mk +--- 16_virtual_mem_part4_higher_half_kernel/kernel_symbols.mk ++++ 17_kernel_symbols/kernel_symbols.mk +@@ -0,0 +1,117 @@ ++## SPDX-License-Identifier: MIT OR Apache-2.0 ++## ++## Copyright (c) 2018-2023 Andre Richter ++ ++include ../common/format.mk ++include ../common/docker.mk ++ ++##-------------------------------------------------------------------------------------------------- ++## Check for input variables that need be exported by the calling Makefile ++##-------------------------------------------------------------------------------------------------- ++ifndef KERNEL_SYMBOLS_TOOL_PATH ++$(error KERNEL_SYMBOLS_TOOL_PATH is not set) ++endif ++ ++ifndef TARGET ++$(error TARGET is not set) ++endif ++ ++ifndef KERNEL_SYMBOLS_INPUT_ELF ++$(error KERNEL_SYMBOLS_INPUT_ELF is not set) ++endif ++ ++ifndef KERNEL_SYMBOLS_OUTPUT_ELF ++$(error KERNEL_SYMBOLS_OUTPUT_ELF is not set) ++endif ++ ++ ++ ++##-------------------------------------------------------------------------------------------------- ++## Targets and Prerequisites ++##-------------------------------------------------------------------------------------------------- ++KERNEL_SYMBOLS_MANIFEST = kernel_symbols/Cargo.toml ++KERNEL_SYMBOLS_LINKER_SCRIPT = kernel_symbols/kernel_symbols.ld ++ ++KERNEL_SYMBOLS_RS = $(KERNEL_SYMBOLS_INPUT_ELF)_symbols.rs ++KERNEL_SYMBOLS_DEMANGLED_RS = $(shell pwd)/$(KERNEL_SYMBOLS_INPUT_ELF)_symbols_demangled.rs ++ ++KERNEL_SYMBOLS_ELF = target/$(TARGET)/release/kernel_symbols ++KERNEL_SYMBOLS_STRIPPED = target/$(TARGET)/release/kernel_symbols_stripped ++ ++# Export for build.rs of kernel_symbols crate. ++export KERNEL_SYMBOLS_DEMANGLED_RS ++ ++ ++ ++##-------------------------------------------------------------------------------------------------- ++## Command building blocks ++##-------------------------------------------------------------------------------------------------- ++GET_SYMBOLS_SECTION_VIRT_ADDR = $(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) \ ++ --get_symbols_section_virt_addr $(KERNEL_SYMBOLS_OUTPUT_ELF) ++ ++RUSTFLAGS = -C link-arg=--script=$(KERNEL_SYMBOLS_LINKER_SCRIPT) \ ++ -C link-arg=--section-start=.rodata=$$($(GET_SYMBOLS_SECTION_VIRT_ADDR)) ++ ++RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ ++ -D warnings \ ++ -D missing_docs ++ ++COMPILER_ARGS = --target=$(TARGET) \ ++ --release ++ ++RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_SYMBOLS_MANIFEST) ++OBJCOPY_CMD = rust-objcopy \ ++ --strip-all \ ++ -O binary ++ ++EXEC_SYMBOLS_TOOL = ruby $(KERNEL_SYMBOLS_TOOL_PATH)/main.rb ++ ++##------------------------------------------------------------------------------ ++## Dockerization ++##------------------------------------------------------------------------------ ++DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial ++ ++# DOCKER_IMAGE defined in include file (see top of this file). ++DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) ++ ++ ++ ++##-------------------------------------------------------------------------------------------------- ++## Targets ++##-------------------------------------------------------------------------------------------------- ++.PHONY: all symbols measure_time_start measure_time_finish ++ ++all: measure_time_start symbols measure_time_finish ++ ++symbols: ++ @cp $(KERNEL_SYMBOLS_INPUT_ELF) $(KERNEL_SYMBOLS_OUTPUT_ELF) ++ ++ @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --gen_symbols $(KERNEL_SYMBOLS_OUTPUT_ELF) \ ++ $(KERNEL_SYMBOLS_RS) ++ ++ $(call color_progress_prefix, "Demangling") ++ @echo Symbol names ++ @cat $(KERNEL_SYMBOLS_RS) | rustfilt > $(KERNEL_SYMBOLS_DEMANGLED_RS) ++ ++ @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ++ ++ $(call color_progress_prefix, "Stripping") ++ @echo Symbols ELF file ++ @$(OBJCOPY_CMD) $(KERNEL_SYMBOLS_ELF) $(KERNEL_SYMBOLS_STRIPPED) ++ ++ @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --patch_data $(KERNEL_SYMBOLS_OUTPUT_ELF) \ ++ $(KERNEL_SYMBOLS_STRIPPED) ++ ++# Note: The following is the only _trivial_ way I could think of that works out of the box on both ++# Linux and macOS. Since macOS does not have the moduloN nanosecond format string option, the ++# resolution is restricted to whole seconds. ++measure_time_start: ++ @date +modulos > /tmp/kernel_symbols_start.date ++ ++measure_time_finish: ++ @date +modulos > /tmp/kernel_symbols_end.date ++ ++ $(call color_progress_prefix, "Finished") ++ @echo "in $$((`cat /tmp/kernel_symbols_end.date` - `cat /tmp/kernel_symbols_start.date`)).0s" ++ ++ @rm /tmp/kernel_symbols_end.date /tmp/kernel_symbols_start.date + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/libraries/debug-symbol-types/Cargo.toml 17_kernel_symbols/libraries/debug-symbol-types/Cargo.toml +--- 16_virtual_mem_part4_higher_half_kernel/libraries/debug-symbol-types/Cargo.toml ++++ 17_kernel_symbols/libraries/debug-symbol-types/Cargo.toml +@@ -0,0 +1,4 @@ ++[package] ++name = "debug-symbol-types" ++version = "0.1.0" ++edition = "2021" + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/libraries/debug-symbol-types/src/lib.rs 17_kernel_symbols/libraries/debug-symbol-types/src/lib.rs +--- 16_virtual_mem_part4_higher_half_kernel/libraries/debug-symbol-types/src/lib.rs ++++ 17_kernel_symbols/libraries/debug-symbol-types/src/lib.rs +@@ -0,0 +1,45 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Types for implementing debug symbol support. ++ ++#![no_std] ++ ++use core::ops::Range; ++ ++/// A symbol containing a size. ++#[repr(C)] ++#[derive(Clone)] ++pub struct Symbol { ++ addr_range: Range, ++ name: &'static str, ++} ++ ++impl Symbol { ++ /// Create an instance. ++ pub const fn new(start: usize, size: usize, name: &'static str) -> Symbol { ++ Symbol { ++ addr_range: Range { ++ start, ++ end: start + size, ++ }, ++ name, ++ } ++ } ++ ++ /// Returns true if addr is contained in the range. ++ pub fn contains(&self, addr: usize) -> bool { ++ self.addr_range.contains(&addr) ++ } ++ ++ /// Returns the symbol's name. ++ pub fn name(&self) -> &'static str { ++ self.name ++ } ++ ++ /// Returns the symbol's size. ++ pub fn size(&self) -> usize { ++ self.addr_range.end - self.addr_range.start ++ } ++} + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/Makefile 17_kernel_symbols/Makefile +--- 16_virtual_mem_part4_higher_half_kernel/Makefile ++++ 17_kernel_symbols/Makefile +@@ -85,7 +85,24 @@ + KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables + KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) + +-KERNEL_ELF = $(KERNEL_ELF_TTABLES) ++##------------------------------------------------------------------------------ ++## Kernel symbols ++##------------------------------------------------------------------------------ ++export KERNEL_SYMBOLS_TOOL_PATH = tools/kernel_symbols_tool ++ ++KERNEL_ELF_TTABLES_SYMS = target/$(TARGET)/release/kernel+ttables+symbols ++ ++# Unlike with KERNEL_ELF_RAW, we are not relying on dep-info here. One of the reasons being that the ++# name of the generated symbols file varies between runs, which can cause confusion. ++KERNEL_ELF_TTABLES_SYMS_DEPS = $(KERNEL_ELF_TTABLES) \ ++ $(wildcard kernel_symbols/*) \ ++ $(wildcard $(KERNEL_SYMBOLS_TOOL_PATH)/*) ++ ++export TARGET ++export KERNEL_SYMBOLS_INPUT_ELF = $(KERNEL_ELF_TTABLES) ++export KERNEL_SYMBOLS_OUTPUT_ELF = $(KERNEL_ELF_TTABLES_SYMS) ++ ++KERNEL_ELF = $(KERNEL_ELF_TTABLES_SYMS) + + + +@@ -178,11 +195,18 @@ + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) + + ##------------------------------------------------------------------------------ ++## Generate kernel symbols and patch them into the kernel ELF ++##------------------------------------------------------------------------------ ++$(KERNEL_ELF_TTABLES_SYMS): $(KERNEL_ELF_TTABLES_SYMS_DEPS) ++ $(call color_header, "Generating kernel symbols and patching kernel ELF") ++ @$(MAKE) --no-print-directory -f kernel_symbols.mk ++ ++##------------------------------------------------------------------------------ + ## Generate the stripped kernel binary + ##------------------------------------------------------------------------------ +-$(KERNEL_BIN): $(KERNEL_ELF_TTABLES) ++$(KERNEL_BIN): $(KERNEL_ELF_TTABLES_SYMS) + $(call color_header, "Generating stripped binary") +- @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) ++ @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES_SYMS) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") +@@ -191,7 +215,7 @@ + ##------------------------------------------------------------------------------ + ## Generate the documentation + ##------------------------------------------------------------------------------ +-doc: ++doc: clean + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +@@ -318,10 +342,19 @@ + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') ++ TEST_ELF_SYMS="$${TEST_ELF}_syms" + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null +- $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY ++ ++ # This overrides the two ENV variables. The other ENV variables that are required as input for ++ # the .mk file are set already because they are exported by this Makefile and this script is ++ # started by the same. ++ KERNEL_SYMBOLS_INPUT_ELF=$$TEST_ELF \ ++ KERNEL_SYMBOLS_OUTPUT_ELF=$$TEST_ELF_SYMS \ ++ $(MAKE) --no-print-directory -f kernel_symbols.mk > /dev/null 2>&1 ++ ++ $(OBJCOPY_CMD) $$TEST_ELF_SYMS $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY + endef + + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/tools/kernel_symbols_tool/cmds.rb 17_kernel_symbols/tools/kernel_symbols_tool/cmds.rb +--- 16_virtual_mem_part4_higher_half_kernel/tools/kernel_symbols_tool/cmds.rb ++++ 17_kernel_symbols/tools/kernel_symbols_tool/cmds.rb +@@ -0,0 +1,45 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2022-2023 Andre Richter ++ ++def generate_symbols(kernel_elf, output_file) ++ File.open(output_file, 'w') do |file| ++ header = <<~HEREDOC ++ use debug_symbol_types::Symbol; ++ ++ # [no_mangle] ++ # [link_section = ".rodata.symbol_desc"] ++ static KERNEL_SYMBOLS: [Symbol; #{kernel_elf.num_symbols}] = [ ++ HEREDOC ++ ++ file.write(header) ++ kernel_elf.symbols.each do |sym| ++ value = sym.header.st_value ++ size = sym.header.st_size ++ name = sym.name ++ ++ file.write(" Symbol::new(#{value}, #{size}, \"#{name}\"),\n") ++ end ++ file.write("];\n") ++ end ++end ++ ++def get_symbols_section_virt_addr(kernel_elf) ++ kernel_elf.kernel_symbols_section_virt_addr ++end ++ ++def patch_symbol_data(kernel_elf, symbols_blob_path) ++ symbols_blob = File.binread(symbols_blob_path) ++ ++ raise if symbols_blob.size > kernel_elf.kernel_symbols_section_size ++ ++ File.binwrite(kernel_elf.path, File.binread(symbols_blob_path), ++ kernel_elf.kernel_symbols_section_offset_in_file) ++end ++ ++def patch_num_symbols(kernel_elf) ++ num_packed = [kernel_elf.num_symbols].pack('Q<*') # "Q" == uint64_t, "<" == little endian ++ File.binwrite(kernel_elf.path, num_packed, kernel_elf.num_kernel_symbols_offset_in_file) ++end + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/tools/kernel_symbols_tool/kernel_elf.rb 17_kernel_symbols/tools/kernel_symbols_tool/kernel_elf.rb +--- 16_virtual_mem_part4_higher_half_kernel/tools/kernel_symbols_tool/kernel_elf.rb ++++ 17_kernel_symbols/tools/kernel_symbols_tool/kernel_elf.rb +@@ -0,0 +1,74 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2021-2023 Andre Richter ++ ++# KernelELF ++class KernelELF ++ attr_reader :path ++ ++ def initialize(kernel_elf_path, kernel_symbols_section, num_kernel_symbols) ++ @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) ++ @symtab_section = @elf.section_by_name('.symtab') ++ ++ @path = kernel_elf_path ++ fetch_values(kernel_symbols_section, num_kernel_symbols) ++ end ++ ++ private ++ ++ def fetch_values(kernel_symbols_section, num_kernel_symbols) ++ sym = @symtab_section.symbol_by_name(num_kernel_symbols) ++ raise "Symbol \"#{num_kernel_symbols}\" not found" if sym.nil? ++ ++ @num_kernel_symbols = sym ++ ++ section = @elf.section_by_name(kernel_symbols_section) ++ raise "Section \"#{kernel_symbols_section}\" not found" if section.nil? ++ ++ @kernel_symbols_section = section ++ end ++ ++ def num_kernel_symbols_virt_addr ++ @num_kernel_symbols.header.st_value ++ end ++ ++ def segment_containing_virt_addr(virt_addr) ++ @elf.each_segments do |segment| ++ return segment if segment.vma_in?(virt_addr) ++ end ++ end ++ ++ def virt_addr_to_file_offset(virt_addr) ++ segment = segment_containing_virt_addr(virt_addr) ++ segment.vma_to_offset(virt_addr) ++ end ++ ++ public ++ ++ def symbols ++ non_zero_symbols = @symtab_section.symbols.reject { |sym| sym.header.st_size.zero? } ++ non_zero_symbols.sort_by { |sym| sym.header.st_value } ++ end ++ ++ def num_symbols ++ symbols.size ++ end ++ ++ def kernel_symbols_section_virt_addr ++ @kernel_symbols_section.header.sh_addr.to_i ++ end ++ ++ def kernel_symbols_section_size ++ @kernel_symbols_section.header.sh_size.to_i ++ end ++ ++ def kernel_symbols_section_offset_in_file ++ virt_addr_to_file_offset(kernel_symbols_section_virt_addr) ++ end ++ ++ def num_kernel_symbols_offset_in_file ++ virt_addr_to_file_offset(num_kernel_symbols_virt_addr) ++ end ++end + +diff -uNr 16_virtual_mem_part4_higher_half_kernel/tools/kernel_symbols_tool/main.rb 17_kernel_symbols/tools/kernel_symbols_tool/main.rb +--- 16_virtual_mem_part4_higher_half_kernel/tools/kernel_symbols_tool/main.rb ++++ 17_kernel_symbols/tools/kernel_symbols_tool/main.rb +@@ -0,0 +1,47 @@ ++#!/usr/bin/env ruby ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2022-2023 Andre Richter ++ ++require 'rubygems' ++require 'bundler/setup' ++require 'colorize' ++require 'elftools' ++ ++require_relative 'kernel_elf' ++require_relative 'cmds' ++ ++KERNEL_SYMBOLS_SECTION = '.kernel_symbols' ++NUM_KERNEL_SYMBOLS = 'NUM_KERNEL_SYMBOLS' ++ ++cmd = ARGV[0] ++ ++kernel_elf_path = ARGV[1] ++kernel_elf = KernelELF.new(kernel_elf_path, KERNEL_SYMBOLS_SECTION, NUM_KERNEL_SYMBOLS) ++ ++case cmd ++when '--gen_symbols' ++ output_file = ARGV[2] ++ ++ print 'Generating'.rjust(12).green.bold ++ puts ' Symbols source file' ++ ++ generate_symbols(kernel_elf, output_file) ++when '--get_symbols_section_virt_addr' ++ addr = get_symbols_section_virt_addr(kernel_elf) ++ ++ puts "0x#{addr.to_s(16)}" ++when '--patch_data' ++ symbols_blob_path = ARGV[2] ++ num_symbols = kernel_elf.num_symbols ++ ++ print 'Patching'.rjust(12).green.bold ++ puts " Symbols blob and number of symbols (#{num_symbols}) into ELF" ++ ++ patch_symbol_data(kernel_elf, symbols_blob_path) ++ patch_num_symbols(kernel_elf) ++else ++ raise ++end + +``` diff --git a/17_kernel_symbols/kernel/Cargo.toml b/17_kernel_symbols/kernel/Cargo.toml new file mode 100644 index 000000000..58bf54d25 --- /dev/null +++ b/17_kernel_symbols/kernel/Cargo.toml @@ -0,0 +1,58 @@ +[package] +name = "mingo" +version = "0.17.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } +debug-symbol-types = { path = "../libraries/debug-symbol-types" } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##-------------------------------------------------------------------------------------------------- +## Testing +##-------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false diff --git a/17_kernel_symbols/kernel/build.rs b/17_kernel_symbols/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/17_kernel_symbols/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/cpu.rs b/17_kernel_symbols/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.rs b/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..4d7b77357 --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use crate::{memory, memory::Address}; +use aarch64_cpu::{asm, registers::*}; +use core::arch::global_asm; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(virt_kernel_init_addr); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(virt_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) -> ! { + prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr, + virt_kernel_init_addr, + ); + + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + + // Use `eret` to "return" to EL1. Since virtual memory will already be enabled, this results in + // execution of kernel_init() in EL1 from its _virtual address_. + asm::eret() +} diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.s b/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..1a8c88010 --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +// Load the address of a symbol into a register, absolute. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_ABS register, symbol + movz \register, #:abs_g3:\symbol + movk \register, #:abs_g2_nc:\symbol + movk \register, #:abs_g1_nc:\symbol + movk \register, #:abs_g0_nc:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Load the base address of the kernel's translation tables. + ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + + // Load the _absolute_ addresses of the following symbols. Since the kernel is linked at + // the top of the 64 bit address space, these are effectively virtual addresses. + ADR_ABS x1, __boot_core_stack_end_exclusive + ADR_ABS x2, kernel_init + + // Load the PC-relative address of the stack and set the stack pointer. + // + // Since _start() is the first function that runs after the firmware has loaded the kernel + // into memory, retrieving this symbol PC-relative returns the "physical" address. + // + // Setting the stack pointer to this value ensures that anything that still runs in EL2, + // until the kernel returns to EL1 with the MMU enabled, works as well. After the return to + // EL1, the virtual address of the stack retrieved above will be used. + ADR_REL x3, __boot_core_stack_end_exclusive + mov sp, x3 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x4, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x5, CNTFRQ_EL0 + cmp x5, xzr + b.eq .L_parking_loop + str w5, [x4] + + // Jump to Rust code. x0, x1 and x2 hold the function arguments provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/smp.rs b/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/smp.rs new file mode 100644 index 000000000..491920389 --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/exception.rs b/17_kernel_symbols/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..d7863a1e6 --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,321 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use crate::{exception, memory, symbols}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!(include_str!("exception.s")); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!( + f, + " Symbol: {}", + match symbols::lookup_symbol(memory::Address::new(self.elr_el1 as usize)) { + Some(sym) => sym.name(), + _ => "Symbol not found", + } + )?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/exception.s b/17_kernel_symbols/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..91805ee7c --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 17 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/exception/asynchronous.rs b/17_kernel_symbols/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..811ef138e --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/memory/mmu.rs b/17_kernel_symbols/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..984b2e04f --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::{mmu::TranslationGranule, Address, Physical}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + #[inline(always)] + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + #[inline(always)] + fn configure_translation_control(&self) { + let t1sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI1::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG1::KiB_64 + + TCR_EL1::SH1::Inner + + TCR_EL1::ORGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD1::EnableTTBR1Walks + + TCR_EL1::A1::TTBR1 + + TCR_EL1::T1SZ.val(t1sz) + + TCR_EL1::EPD0::DisableTTBR0Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Set the "Translation Table Base Register". + TTBR1_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/17_kernel_symbols/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..21fae3b82 --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,521 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, + memory::{ + self, + mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, + }, + Address, Physical, Virtual, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn virt_start_addr(&self) -> Address; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], + + /// Have the tables been initialized? + initialized: bool, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl StartAddr for [T; N] { + fn virt_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +/// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. +impl convert::TryFrom> for AttributeFields { + type Error = &'static str; + + fn try_from( + desc: InMemoryRegister, + ) -> Result { + let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { + memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, + memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, + _ => return Err("Unexpected memory attribute"), + }; + + let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, + _ => return Err("Unexpected access permission"), + }; + + let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; + + Ok(AttributeFields { + mem_attributes, + acc_perms, + execute_never, + }) + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_page_addr( + phys_output_page_addr: PageAddress, + attribute_fields: &AttributeFields, + ) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } + + /// Returns the valid bit. + fn is_valid(&self) -> bool { + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } + + /// Returns the output page. + fn output_page_addr(&self) -> PageAddress { + let shifted = InMemoryRegister::::new(self.value) + .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; + + PageAddress::from(shifted << Granule64KiB::SHIFT) + } + + /// Returns the attributes. + fn try_attributes(&self) -> Result { + InMemoryRegister::::new(self.value).try_into() + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromTop = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; + + type TableStartFromBottom = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; +} + +impl + FixedSizeTranslationTable +{ + const START_FROM_TOP_OFFSET: Address = + Address::new((usize::MAX - (Granule512MiB::SIZE * NUM_TABLES)) + 1); + + /// Create an instance. + #[allow(clippy::assertions_on_constants)] + const fn _new(for_precompute: bool) -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + initialized: for_precompute, + } + } + + pub const fn new_for_precompute() -> Self { + Self::_new(true) + } + + #[cfg(test)] + pub fn new_for_runtime() -> Self { + Self::_new(false) + } + + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { + let mut addr = virt_page_addr.into_inner(); + + if START_FROM_TOP { + addr = addr - Self::START_FROM_TOP_OFFSET; + } + + let lvl2_index = addr.as_usize() >> Granule512MiB::SHIFT; + let lvl3_index = (addr.as_usize() & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); + } + + Ok((lvl2_index, lvl3_index)) + } + + /// Returns the PageDescriptor corresponding to the supplied page address. + #[inline(always)] + fn page_descriptor_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<&PageDescriptor, &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &self.lvl3[lvl2_index][lvl3_index]; + + Ok(desc) + } + + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. + #[inline(always)] + fn set_page_descriptor_from_page_addr( + &mut self, + virt_page_addr: PageAddress, + new_desc: &PageDescriptor, + ) -> Result<(), &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &mut self.lvl3[lvl2_index][lvl3_index]; + + if desc.is_valid() { + return Err("Virtual page is already mapped"); + } + + *desc = *new_desc; + Ok(()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl + memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable +{ + fn init(&mut self) -> Result<(), &'static str> { + if self.initialized { + return Ok(()); + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { + let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); + let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; + + Ok(()) + } + + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + assert!(self.initialized, "Translation tables not initialized"); + + if virt_region.size() != phys_region.size() { + return Err("Tried to map memory regions with unequal sizes"); + } + + if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() + { + return Err("Tried to map outside of physical address space"); + } + + let iter = phys_region.into_iter().zip(virt_region.into_iter()); + for (phys_page_addr, virt_page_addr) in iter { + let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); + let virt_page = virt_page_addr; + + self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; + } + + Ok(()) + } + + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str> { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + Ok(page_desc.output_page_addr()) + } + + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + page_desc.try_attributes() + } + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str> { + let virt_page = PageAddress::from(virt_addr.align_down_page()); + let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; + + Ok(phys_page.into_inner() + virt_addr.offset_into_page()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1, true>; + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/17_kernel_symbols/kernel/src/_arch/aarch64/time.rs b/17_kernel_symbols/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/17_kernel_symbols/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/17_kernel_symbols/kernel/src/bsp.rs b/17_kernel_symbols/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver.rs b/17_kernel_symbols/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..2dfaec8d6 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(feature = "bsp_rpi4")] +mod arm; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/arm.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/arm.rs new file mode 100644 index 000000000..8d1cbfbd8 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2.rs new file mode 100644 index 000000000..256de7041 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new( + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, + ) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs new file mode 100644 index 000000000..0fd16bb38 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs new file mode 100644 index 000000000..1fc9d70e9 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, + state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num % 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/bcm.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..7b7c288b7 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..812156f44 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs new file mode 100644 index 000000000..62f078002 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.periph.print_handler(); + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs new file mode 100644 index 000000000..a26bff8d0 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), + } + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() % 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..b424d4be7 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/device_driver/common.rs b/17_kernel_symbols/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..3ce1d8d81 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use crate::memory::{Address, Virtual}; +use core::{fmt, marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: Address, + phantom: PhantomData T>, +} + +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: Address) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr.as_usize() as *const _) } + } +} + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi.rs b/17_kernel_symbols/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..30421dfa6 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi/cpu.rs b/17_kernel_symbols/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi/driver.rs b/17_kernel_symbols/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..a1f55b170 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, + memory, + memory::mmu::MMIODescriptor, +}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering}, +}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi3")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi4")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the UART driver. +unsafe fn post_init_uart() -> Result<(), &'static str> { + console::register_console(PL011_UART.assume_init_ref()); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_gpio() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; + + GPIO.write(device_driver::GPIO::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +unsafe fn post_init_gpio() -> Result<(), &'static str> { + GPIO.assume_init_ref().map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi3")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &periph_mmio_descriptor, + )?; + + INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi4")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); + let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; + + let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); + let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; + + INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the interrupt controller driver. +unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_gpio() -> Result<(), &'static str> { + instantiate_gpio()?; + + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( + GPIO.assume_init_ref(), + Some(post_init_gpio), + None, + ); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { + instantiate_interrupt_controller()?; + + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + INTERRUPT_CONTROLLER.assume_init_ref(), + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + use crate::cpu; + + unsafe { + instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); + console::register_console(PL011_UART.assume_init_ref()); + }; +} diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi/exception.rs b/17_kernel_symbols/kernel/src/bsp/raspberrypi/exception.rs new file mode 100644 index 000000000..a9eaa6ac4 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/17_kernel_symbols/kernel/src/bsp/raspberrypi/exception/asynchronous.rs new file mode 100644 index 000000000..776182fd0 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +#[cfg(feature = "bsp_rpi3")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; + + pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +#[cfg(feature = "bsp_rpi4")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::IRQNumber; + + pub const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel.ld b/17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..193a5200b --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,121 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +INCLUDE kernel_virt_addr_space_size.ld; + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +/* The kernel's virtual address range will be: + * + * [END_ADDRESS_INCLUSIVE, START_ADDRESS] + * [u64::MAX , (u64::MAX - __kernel_virt_addr_space_size) + 1] + */ +__kernel_virt_start_addr = ((0xffffffffffffffff - __kernel_virt_addr_space_size) + 1); + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); + segment_boot_core_stack PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __kernel_virt_start_addr; + + ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : AT(__rpi_phys_binary_load_addr) + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + .kernel_symbols : ALIGN(8) { + __kernel_symbols_start = .; + . += 32 * 1024; + } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + __data_start = .; + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + + /*********************************************************************************************** + * Guard Page + ***********************************************************************************************/ + . += PAGE_SIZE; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) + { + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld b/17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld new file mode 100644 index 000000000..c5d58c30a --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld @@ -0,0 +1 @@ +__kernel_virt_addr_space_size = 1024 * 1024 * 1024 diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi/memory.rs b/17_kernel_symbols/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..96a4d8c1c --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | .kernel_symbols | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | data_end_exclusive +//! | | +//! +//! +//! +//! +//! +//! The virtual memory layout is as follows: +//! +//! +---------------------------------------+ +//! | | code_start @ __kernel_virt_start_addr +//! | .text | +//! | .rodata | +//! | .got | +//! | .kernel_symbols | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_start == data_end_exclusive +//! | VA region for MMIO remapping | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_end_exclusive +//! | Unmapped guard page | +//! | | +//! +---------------------------------------+ +//! | | boot_core_stack_start +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | boot_core_stack_end_exclusive +//! | | +pub mod mmu; + +use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; + + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + + static __boot_core_stack_start: UnsafeCell<()>; + static __boot_core_stack_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + use super::*; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); + pub const PERIPHERAL_IC_SIZE: usize = 0x24; + + pub const GPIO_START: Address = Address::new(0x3F20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const END: Address = Address::new(0x4001_0000); + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const GPIO_START: Address = Address::new(0xFE20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0xFE20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const GICD_START: Address = Address::new(0xFF84_1000); + pub const GICD_SIZE: usize = 0x824; + + pub const GICC_START: Address = Address::new(0xFF84_2000); + pub const GICC_SIZE: usize = 0x14; + + pub const END: Address = Address::new(0xFF85_0000); + } + + pub const END: Address = mmio::END; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_code_start() -> PageAddress { + PageAddress::from(unsafe { __code_start.get() as usize }) +} + +/// Size of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_size() -> usize { + unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } +} + +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { + PageAddress::from(unsafe { __data_start.get() as usize }) +} + +/// Size of the data segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn data_size() -> usize { + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } +} + +/// Start page address of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_mmio_remap_start() -> PageAddress { + PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) +} + +/// Size of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn mmio_remap_size() -> usize { + unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } +} + +/// Start page address of the boot core's stack. +#[inline(always)] +fn virt_boot_core_stack_start() -> PageAddress { + PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) +} + +/// Size of the boot core's stack. +#[inline(always)] +fn boot_core_stack_size() -> usize { + unsafe { + (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Exclusive end address of the physical address space. +#[inline(always)] +pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { + PageAddress::from(map::END) +} diff --git a/17_kernel_symbols/kernel/src/bsp/raspberrypi/memory/mmu.rs b/17_kernel_symbols/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..3c0368b91 --- /dev/null +++ b/17_kernel_symbols/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use crate::{ + memory::{ + mmu::{ + self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, + MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type KernelTranslationTable = + ::TableStartFromTop; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to +/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. +pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + +/// The kernel's virtual address space defined by this BSP. +pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// It is mandatory that InitStateLock is transparent. +/// +/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. +/// There is a unit tests that checks this porperty. +#[link_section = ".data"] +#[no_mangle] +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new_for_precompute()); + +/// This value is needed during early boot for MMU setup. +/// +/// This will be patched to the correct value by the "translation table tool" after linking. This +/// given value here is just a dummy. +#[link_section = ".text._start_arguments"] +#[no_mangle] +static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This is a hack for retrieving the value for the kernel's virtual address space size as a +/// constant from a common place, since it is needed as a compile-time/link-time constant in both, +/// the linker script and the Rust sources. +#[allow(clippy::needless_late_init)] +const fn kernel_virt_addr_space_size() -> usize { + let __kernel_virt_addr_space_size; + + include!("../kernel_virt_addr_space_size.ld"); + + __kernel_virt_addr_space_size +} + +/// Helper function for calculating the number of pages the given parameter spans. +const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); + assert!(size % KernelGranule::SIZE == 0); + + size >> KernelGranule::SHIFT +} + +/// The code pages of the kernel binary. +fn virt_code_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::code_size()); + + let start_page_addr = super::virt_code_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The data pages of the kernel binary. +fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); + + let start_page_addr = super::virt_data_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The boot core stack pages. +fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); + + let start_page_addr = super::virt_boot_core_stack_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +// There is no reason to expect the following conversions to fail, since they were generated offline +// by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. +fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { + let phys_start_page_addr = + generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) + .unwrap(); + + let phys_end_exclusive_page_addr = phys_start_page_addr + .checked_offset(virt_region.num_pages() as isize) + .unwrap(); + + MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) +} + +fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { + generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} + +/// The MMIO remap pages. +pub fn virt_mmio_remap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::mmio_remap_size()); + + let start_page_addr = super::virt_mmio_remap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Add mapping records for the kernel binary. +/// +/// The actual translation table entries for the kernel binary are generated using the offline +/// `translation table tool` and patched into the kernel binary. This function just adds the mapping +/// record entries. +pub fn kernel_add_mapping_records_for_precomputed() { + let virt_code_region = virt_code_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel code and RO data", + &virt_code_region, + &kernel_virt_to_phys_region(virt_code_region), + &kernel_page_attributes(virt_code_region.start_page_addr()), + ); + + let virt_data_region = virt_data_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel data and bss", + &virt_data_region, + &kernel_virt_to_phys_region(virt_data_region), + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); + + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", + &virt_boot_core_stack_region, + &kernel_virt_to_phys_region(virt_boot_core_stack_region), + &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), + ); +} diff --git a/17_kernel_symbols/kernel/src/common.rs b/17_kernel_symbols/kernel/src/common.rs new file mode 100644 index 000000000..2ad7e4c1e --- /dev/null +++ b/17_kernel_symbols/kernel/src/common.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Check if a value is aligned to a given size. +#[inline(always)] +pub const fn is_aligned(value: usize, alignment: usize) -> bool { + assert!(alignment.is_power_of_two()); + + (value & (alignment - 1)) == 0 +} + +/// Align down. +#[inline(always)] +pub const fn align_down(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + value & !(alignment - 1) +} + +/// Align up. +#[inline(always)] +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + (value + alignment - 1) & !(alignment - 1) +} + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/17_kernel_symbols/kernel/src/console.rs b/17_kernel_symbols/kernel/src/console.rs new file mode 100644 index 000000000..f03634649 --- /dev/null +++ b/17_kernel_symbols/kernel/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.read(|con| *con) +} diff --git a/17_kernel_symbols/kernel/src/console/null_console.rs b/17_kernel_symbols/kernel/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/17_kernel_symbols/kernel/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/17_kernel_symbols/kernel/src/cpu.rs b/17_kernel_symbols/kernel/src/cpu.rs new file mode 100644 index 000000000..8716a918b --- /dev/null +++ b/17_kernel_symbols/kernel/src/cpu.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +pub mod smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/17_kernel_symbols/kernel/src/cpu/boot.rs b/17_kernel_symbols/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/17_kernel_symbols/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/17_kernel_symbols/kernel/src/cpu/smp.rs b/17_kernel_symbols/kernel/src/cpu/smp.rs new file mode 100644 index 000000000..de612d589 --- /dev/null +++ b/17_kernel_symbols/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff --git a/17_kernel_symbols/kernel/src/driver.rs b/17_kernel_symbols/kernel/src/driver.rs new file mode 100644 index 000000000..2edf8b854 --- /dev/null +++ b/17_kernel_symbols/kernel/src/driver.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner +where + T: 'static, +{ + next_index: usize, + descriptors: [Option>; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager +where + T: 'static, +{ + inner: InitStateLock>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner +where + T: 'static + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + irq_number, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager +where + T: fmt::Display + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: InitStateLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.write(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.read(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + self.for_each_descriptor(|descriptor| { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/17_kernel_symbols/kernel/src/exception.rs b/17_kernel_symbols/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/17_kernel_symbols/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/17_kernel_symbols/kernel/src/exception/asynchronous.rs b/17_kernel_symbols/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..2c874dd60 --- /dev/null +++ b/17_kernel_symbols/kernel/src/exception/asynchronous.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff --git a/17_kernel_symbols/kernel/src/exception/asynchronous/null_irq_manager.rs b/17_kernel_symbols/kernel/src/exception/asynchronous/null_irq_manager.rs new file mode 100644 index 000000000..38919ffe4 --- /dev/null +++ b/17_kernel_symbols/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff --git a/17_kernel_symbols/kernel/src/lib.rs b/17_kernel_symbols/kernel/src/lib.rs new file mode 100644 index 000000000..54e581a27 --- /dev/null +++ b/17_kernel_symbols/kernel/src/lib.rs @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(generic_const_exprs)] +#![feature(int_roundings)] +#![feature(is_sorted)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(step_trait)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +mod panic_wait; +mod synchronization; + +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod state; +pub mod symbols; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/17_kernel_symbols/kernel/src/main.rs b/17_kernel_symbols/kernel/src/main.rs new file mode 100644 index 000000000..e41cfaa0d --- /dev/null +++ b/17_kernel_symbols/kernel/src/main.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + +/// Early init code. +/// +/// When this code runs, virtual memory is already enabled. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - Printing will not work until the respective driver's MMIO is remapped. +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + + bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online:"); + memory::mmu::kernel_print_mappings(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + + info!("Echoing input now"); + cpu::wait_forever(); +} diff --git a/17_kernel_symbols/kernel/src/memory.rs b/17_kernel_symbols/kernel/src/memory.rs new file mode 100644 index 000000000..6131bdb6c --- /dev/null +++ b/17_kernel_symbols/kernel/src/memory.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; + +use crate::{bsp, common}; +use core::{ + fmt, + marker::PhantomData, + ops::{Add, Sub}, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Physical {} + +/// Zero-sized type to mark a virtual address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl AddressType for Physical {} +impl AddressType for Virtual {} + +impl Address { + /// Create an instance. + pub const fn new(value: usize) -> Self { + Self { + value, + _address_type: PhantomData, + } + } + + /// Convert to usize. + pub const fn as_usize(self) -> usize { + self.value + } + + /// Align down to page size. + #[must_use] + pub const fn align_down_page(self) -> Self { + let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Align up to page size. + #[must_use] + pub const fn align_up_page(self) -> Self { + let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Checks if the address is page aligned. + pub const fn is_page_aligned(&self) -> bool { + common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) + } + + /// Return the address' offset into the corresponding page. + pub const fn offset_into_page(&self) -> usize { + self.value & bsp::memory::mmu::KernelGranule::MASK + } +} + +impl Add for Address { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: usize) -> Self::Output { + match self.value.checked_add(rhs) { + None => panic!("Overflow on Address::add"), + Some(x) => Self::new(x), + } + } +} + +impl Sub> for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Address) -> Self::Output { + match self.value.checked_sub(rhs.value) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q3: u8 = ((self.value >> 32) & 0xff) as u8; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:02x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q4: u16 = ((self.value >> 48) & 0xffff) as u16; + let q3: u16 = ((self.value >> 32) & 0xffff) as u16; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:04x}_", q4)?; + write!(f, "{:04x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of [Address] methods. + #[kernel_test] + fn address_type_method_sanity() { + let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); + + assert_eq!( + addr.align_down_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE + ); + + assert_eq!( + addr.align_up_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + + assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} diff --git a/17_kernel_symbols/kernel/src/memory/mmu.rs b/17_kernel_symbols/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..404e2a8a9 --- /dev/null +++ b/17_kernel_symbols/kernel/src/memory/mmu.rs @@ -0,0 +1,265 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod mapping_record; +mod page_alloc; +mod translation_table; +mod types; + +use crate::{ + bsp, + memory::{Address, Physical, Virtual}, + synchronization::{self, interface::Mutex}, + warn, +}; +use core::{fmt, num::NonZeroUsize}; + +pub use types::*; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Turns on the MMU for the first time and enables data and instruction caching. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] + type TableStartFromTop; + + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +use interface::MMU; +use synchronization::interface::ReadWriteEx; +use translation_table::interface::TranslationTable; + +/// Map a region in the kernel's translation tables. +/// +/// No input checks done, input is passed through to the architectural implementation. +/// +/// # Safety +/// +/// - See `map_at()`. +/// - Does not prevent aliasing. +unsafe fn kernel_map_at_unchecked( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + + kernel_add_mapping_record(name, virt_region, phys_region, attr); + + Ok(()) +} + +/// Try to translate a kernel virtual address to a physical address. +/// +/// Will only succeed if there exists a valid mapping for the input address. +fn try_kernel_virt_addr_to_phys_addr( + virt_addr: Address, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's mask. + pub const MASK: usize = Self::SIZE - 1; + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +pub fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Add an entry to the mapping info record. +pub fn kernel_add_mapping_record( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) { + if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { + warn!("{}", x); + } +} + +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +/// +/// # Safety +/// +/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + let phys_region = MemoryRegion::from(*mmio_descriptor); + let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); + + // Check if an identical region has been mapped for another driver. If so, reuse it. + let virt_addr = if let Some(addr) = + mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) + { + addr + // Otherwise, allocate a new region and map it. + } else { + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, + }; + + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + virt_region.start_addr() + }; + + Ok(virt_addr + offset_into_start_page) +} + +/// Try to translate a kernel virtual page address to a physical page address. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_virt_page_addr_to_phys_page_addr( + virt_page_addr: PageAddress, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) +} + +/// Try to get the attributes of a kernel page. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_page_attributes( + virt_page_addr: PageAddress, +) -> Result { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_page_attributes(virt_page_addr)) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() +} + +/// Enable the MMU and data + instruction caching. +/// +/// # Safety +/// +/// - Crucial function during kernel init. Changes the the complete memory view of the processor. +#[inline(always)] +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) +} diff --git a/17_kernel_symbols/kernel/src/memory/mmu/mapping_record.rs b/17_kernel_symbols/kernel/src/memory/mmu/mapping_record.rs new file mode 100644 index 000000000..0e0792201 --- /dev/null +++ b/17_kernel_symbols/kernel/src/memory/mmu/mapping_record.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + +use super::{ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Type describing a virtual memory mapping. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +struct MappingRecordEntry { + pub users: [Option<&'static str>; 5], + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, + pub attribute_fields: AttributeFields, +} + +struct MappingRecord { + inner: [Option; 12], +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MAPPING_RECORD: InitStateLock = + InitStateLock::new(MappingRecord::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl MappingRecordEntry { + pub fn new( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Self { + Self { + users: [Some(name), None, None, None, None], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), + attribute_fields: *attr, + } + } + + fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { + if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { + return Ok(x); + }; + + Err("Storage for user info exhausted") + } + + pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { + let x = self.find_next_free_user()?; + *x = Some(user); + Ok(()) + } +} + +impl MappingRecord { + pub const fn new() -> Self { + Self { inner: [None; 12] } + } + + fn size(&self) -> usize { + self.inner.iter().filter(|x| x.is_some()).count() + } + + fn sort(&mut self) { + let upper_bound_exclusive = self.size(); + let entries = &mut self.inner[0..upper_bound_exclusive]; + + if !entries.is_sorted_by_key(|item| item.unwrap().virt_start_addr) { + entries.sort_unstable_by_key(|item| item.unwrap().virt_start_addr) + } + } + + fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { + if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { + return Ok(x); + } + + Err("Storage for mapping info exhausted") + } + + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() + .filter_map(|x| x.as_mut()) + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { + return false; + } + + if x.num_pages != phys_region.num_pages() { + return false; + } + + true + }) + } + + pub fn add( + &mut self, + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + let x = self.find_next_free()?; + + *x = Some(MappingRecordEntry::new( + name, + virt_region, + phys_region, + attr, + )); + + self.sort(); + + Ok(()) + } + + pub fn print(&self) { + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", + "Virtual", "Physical", "Size", "Attr", "Entity" + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + + for i in self.inner.iter().flatten() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match i.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if i.attribute_fields.execute_never { + "XN" + } else { + "X" + }; + + info!( + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, + phys_end_inclusive, + size, + unit, + attr, + acc_p, + xn, + i.users[0].unwrap() + ); + + for k in i.users[1..].iter() { + if let Some(additional_user) = *k { + info!( + " | {}", + additional_user + ); + } + } + } + + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +/// Add an entry to the mapping info record. +pub fn kernel_add( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) +} + +pub fn kernel_find_and_insert_mmio_duplicate( + mmio_descriptor: &MMIODescriptor, + new_user: &'static str, +) -> Option> { + let phys_region: MemoryRegion = (*mmio_descriptor).into(); + + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + + if let Err(x) = dup.add_user(new_user) { + warn!("{}", x); + } + + Some(dup.virt_start_addr) + }) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print() { + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} diff --git a/17_kernel_symbols/kernel/src/memory/mmu/page_alloc.rs b/17_kernel_symbols/kernel/src/memory/mmu/page_alloc.rs new file mode 100644 index 000000000..344afd200 --- /dev/null +++ b/17_kernel_symbols/kernel/src/memory/mmu/page_alloc.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Page allocation. + +use super::MemoryRegion; +use crate::{ + memory::{AddressType, Virtual}, + synchronization::IRQSafeNullLock, + warn, +}; +use core::num::NonZeroUsize; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A page allocator that can be lazyily initialized. +pub struct PageAllocator { + pool: Option>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = + IRQSafeNullLock::new(PageAllocator::new()); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's MMIO virtual address allocator. +pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { + &KERNEL_MMIO_VA_ALLOCATOR +} + +impl PageAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { pool: None } + } + + /// Initialize the allocator. + pub fn init(&mut self, pool: MemoryRegion) { + if self.pool.is_some() { + warn!("Already initialized"); + return; + } + + self.pool = Some(pool); + } + + /// Allocate a number of pages. + pub fn alloc( + &mut self, + num_requested_pages: NonZeroUsize, + ) -> Result, &'static str> { + if self.pool.is_none() { + return Err("Allocator not initialized"); + } + + self.pool + .as_mut() + .unwrap() + .take_first_n_pages(num_requested_pages) + } +} diff --git a/17_kernel_symbols/kernel/src/memory/mmu/translation_table.rs b/17_kernel_symbols/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..341ffc5c8 --- /dev/null +++ b/17_kernel_symbols/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +use super::{AttributeFields, MemoryRegion}; +use crate::memory::{Address, Physical, Virtual}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(target_arch = "aarch64")] +pub use arch_translation_table::FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Translation table interfaces. +pub mod interface { + use crate::memory::mmu::PageAddress; + + use super::*; + + /// Translation table operations. + pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self) -> Result<(), &'static str>; + + /// Map the given virtual memory region to the given physical memory region. + /// + /// # Safety + /// + /// - Using wrong attributes can cause multiple issues of different nature in the system. + /// - It is not required that the architectural implementation prevents aliasing. That is, + /// mapping to the same physical memory using multiple virtual addresses, which would + /// break Rust's ownership assumptions. This should be protected against in the kernel's + /// generic MMU code. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; + + /// Try to translate a virtual page address to a physical page address. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str>; + + /// Try to get the attributes of a page. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result; + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str>; + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use arch_translation_table::MinSizeTranslationTable; + use interface::TranslationTable; + use test_macros::kernel_test; + + /// Sanity checks for the TranslationTable implementation. + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. + let mut tables = MinSizeTranslationTable::new_for_runtime(); + + assert_eq!(tables.init(), Ok(())); + + let virt_end_exclusive_page_addr: PageAddress = PageAddress::MAX; + let virt_start_page_addr: PageAddress = + virt_end_exclusive_page_addr.checked_offset(-5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + + let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + + assert_eq!( + tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), + Ok(phys_start_page_addr) + ); + + assert_eq!( + tables.try_page_attributes(virt_start_page_addr.checked_offset(-1).unwrap()), + Err("Page marked invalid") + ); + + assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); + + let virt_addr = virt_start_page_addr.into_inner() + 0x100; + let phys_addr = phys_start_page_addr.into_inner() + 0x100; + assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); + } +} diff --git a/17_kernel_symbols/kernel/src/memory/mmu/types.rs b/17_kernel_symbols/kernel/src/memory/mmu/types.rs new file mode 100644 index 000000000..f6ac8d598 --- /dev/null +++ b/17_kernel_symbols/kernel/src/memory/mmu/types.rs @@ -0,0 +1,378 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + +use crate::{ + bsp, common, + memory::{Address, AddressType, Physical}, +}; +use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct PageAddress { + inner: Address, +} + +/// A type that describes a region of memory in quantities of pages. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// An MMIO descriptor for use in device drivers. +#[derive(Copy, Clone)] +pub struct MMIODescriptor { + start_addr: Address, + end_addr_exclusive: Address, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------ +// PageAddress +//------------------------------------------------------------------------------ +impl PageAddress { + /// The largest value that can be represented by this type. + pub const MAX: Self = PageAddress { + inner: Address::new(usize::MAX).align_down_page(), + }; + + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + } + + /// Calculates the offset from the page address. + /// + /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * + /// page_size`. + pub fn checked_offset(self, count: isize) -> Option { + if count == 0 { + return Some(self); + } + + let delta = count + .unsigned_abs() + .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; + let result = if count.is_positive() { + self.inner.as_usize().checked_add(delta)? + } else { + self.inner.as_usize().checked_sub(delta)? + }; + + Some(Self { + inner: Address::new(result), + }) + } +} + +impl From for PageAddress { + fn from(addr: usize) -> Self { + assert!( + common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), + "Input usize not page aligned" + ); + + Self { + inner: Address::new(addr), + } + } +} + +impl From> for PageAddress { + fn from(addr: Address) -> Self { + assert!(addr.is_page_aligned(), "Input Address not page aligned"); + + Self { inner: addr } + } +} + +impl Step for PageAddress { + fn steps_between(start: &Self, end: &Self) -> Option { + if start > end { + return None; + } + + // Since start <= end, do unchecked arithmetic. + Some( + (end.inner.as_usize() - start.inner.as_usize()) + >> bsp::memory::mmu::KernelGranule::SHIFT, + ) + } + + fn forward_checked(start: Self, count: usize) -> Option { + start.checked_offset(count as isize) + } + + fn backward_checked(start: Self, count: usize) -> Option { + start.checked_offset(-(count as isize)) + } +} + +//------------------------------------------------------------------------------ +// MemoryRegion +//------------------------------------------------------------------------------ +impl MemoryRegion { + /// Create an instance. + pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { + assert!(start <= end_exclusive); + + Self { + start, + end_exclusive, + } + } + + fn as_range(&self) -> Range> { + self.into_iter() + } + + /// Returns the start page address. + pub fn start_page_addr(&self) -> PageAddress { + self.start + } + + /// Returns the start address. + pub fn start_addr(&self) -> Address { + self.start.into_inner() + } + + /// Returns the exclusive end page address. + pub fn end_exclusive_page_addr(&self) -> PageAddress { + self.end_exclusive + } + + /// Returns the exclusive end page address. + pub fn end_inclusive_page_addr(&self) -> PageAddress { + self.end_exclusive.checked_offset(-1).unwrap() + } + + /// Checks if self contains an address. + pub fn contains(&self, addr: Address) -> bool { + let page_addr = PageAddress::from(addr.align_down_page()); + self.as_range().contains(&page_addr) + } + + /// Checks if there is an overlap with another memory region. + pub fn overlaps(&self, other_region: &Self) -> bool { + let self_range = self.as_range(); + + self_range.contains(&other_region.start_page_addr()) + || self_range.contains(&other_region.end_inclusive_page_addr()) + } + + /// Returns the number of pages contained in this region. + pub fn num_pages(&self) -> usize { + PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() + } + + /// Returns the size in bytes of this region. + pub fn size(&self) -> usize { + // Invariant: start <= end_exclusive, so do unchecked arithmetic. + let end_exclusive = self.end_exclusive.into_inner().as_usize(); + let start = self.start.into_inner().as_usize(); + + end_exclusive - start + } + + /// Splits the MemoryRegion like: + /// + /// -------------------------------------------------------------------------------- + /// | | | | | | | | | | | | | | | | | | | + /// -------------------------------------------------------------------------------- + /// ^ ^ ^ + /// | | | + /// left_start left_end_exclusive | + /// | + /// ^ | + /// | | + /// right_start right_end_exclusive + /// + /// Left region is returned to the caller. Right region is the new region for this struct. + pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { + let count: usize = num_pages.into(); + + let left_end_exclusive = self.start.checked_offset(count as isize); + let left_end_exclusive = match left_end_exclusive { + None => return Err("Overflow while calculating left_end_exclusive"), + Some(x) => x, + }; + + if left_end_exclusive > self.end_exclusive { + return Err("Not enough free pages"); + } + + let allocation = Self { + start: self.start, + end_exclusive: left_end_exclusive, + }; + self.start = left_end_exclusive; + + Ok(allocation) + } +} + +impl IntoIterator for MemoryRegion { + type Item = PageAddress; + type IntoIter = Range; + + fn into_iter(self) -> Self::IntoIter { + Range { + start: self.start, + end: self.end_exclusive, + } + } +} + +impl From for MemoryRegion { + fn from(desc: MMIODescriptor) -> Self { + let start = PageAddress::from(desc.start_addr.align_down_page()); + let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); + + Self { + start, + end_exclusive, + } + } +} + +//------------------------------------------------------------------------------ +// MMIODescriptor +//------------------------------------------------------------------------------ + +impl MMIODescriptor { + /// Create an instance. + pub const fn new(start_addr: Address, size: usize) -> Self { + assert!(size > 0); + let end_addr_exclusive = Address::new(start_addr.as_usize() + size); + + Self { + start_addr, + end_addr_exclusive, + } + } + + /// Return the start address. + pub const fn start_addr(&self) -> Address { + self.start_addr + } + + /// Return the exclusive end address. + pub fn end_addr_exclusive(&self) -> Address { + self.end_addr_exclusive + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::Virtual; + use test_macros::kernel_test; + + /// Sanity of [PageAddress] methods. + #[kernel_test] + fn pageaddress_type_method_sanity() { + let page_addr: PageAddress = + PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); + + assert_eq!( + page_addr.checked_offset(-2), + Some(PageAddress::::from(0)) + ); + + assert_eq!( + page_addr.checked_offset(2), + Some(PageAddress::::from( + bsp::memory::mmu::KernelGranule::SIZE * 4 + )) + ); + + assert_eq!( + PageAddress::::from(0).checked_offset(0), + Some(PageAddress::::from(0)) + ); + assert_eq!(PageAddress::::from(0).checked_offset(-1), None); + + let max_page_addr = Address::::new(usize::MAX).align_down_page(); + assert_eq!( + PageAddress::::from(max_page_addr).checked_offset(1), + None + ); + + let zero = PageAddress::::from(0); + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); + } + + /// Sanity of [MemoryRegion] methods. + #[kernel_test] + fn memoryregion_type_method_sanity() { + let zero = PageAddress::::from(0); + let zero_region = MemoryRegion::new(zero, zero); + assert_eq!(zero_region.num_pages(), 0); + assert_eq!(zero_region.size(), 0); + + let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); + let one_region = MemoryRegion::new(zero, one); + assert_eq!(one_region.num_pages(), 1); + assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); + + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + let mut three_region = MemoryRegion::new(zero, three); + assert!(three_region.contains(zero.into_inner())); + assert!(!three_region.contains(three.into_inner())); + assert!(three_region.overlaps(&one_region)); + + let allocation = three_region + .take_first_n_pages(NonZeroUsize::new(2).unwrap()) + .unwrap(); + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + + for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE + ); + } + } +} diff --git a/17_kernel_symbols/kernel/src/panic_wait.rs b/17_kernel_symbols/kernel/src/panic_wait.rs new file mode 100644 index 000000000..c6f3a9c7b --- /dev/null +++ b/17_kernel_symbols/kernel/src/panic_wait.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{cpu, exception, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + + _panic_exit() +} diff --git a/17_kernel_symbols/kernel/src/print.rs b/17_kernel_symbols/kernel/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/17_kernel_symbols/kernel/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/17_kernel_symbols/kernel/src/state.rs b/17_kernel_symbols/kernel/src/state.rs new file mode 100644 index 000000000..6d99beedb --- /dev/null +++ b/17_kernel_symbols/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff --git a/17_kernel_symbols/kernel/src/symbols.rs b/17_kernel_symbols/kernel/src/symbols.rs new file mode 100644 index 000000000..fdc1d084c --- /dev/null +++ b/17_kernel_symbols/kernel/src/symbols.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Debug symbol support. + +use crate::memory::{Address, Virtual}; +use core::{cell::UnsafeCell, slice}; +use debug_symbol_types::Symbol; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbol from the linker script. +extern "Rust" { + static __kernel_symbols_start: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// This will be patched to the correct value by the "kernel symbols tool" after linking. This given +/// value here is just a (safe) dummy. +#[no_mangle] +static NUM_KERNEL_SYMBOLS: u64 = 0; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn kernel_symbol_section_virt_start_addr() -> Address { + Address::new(unsafe { __kernel_symbols_start.get() as usize }) +} + +fn num_kernel_symbols() -> usize { + unsafe { + // Read volatile is needed here to prevent the compiler from optimizing NUM_KERNEL_SYMBOLS + // away. + core::ptr::read_volatile(&NUM_KERNEL_SYMBOLS as *const u64) as usize + } +} + +fn kernel_symbols_slice() -> &'static [Symbol] { + let ptr = kernel_symbol_section_virt_start_addr().as_usize() as *const Symbol; + + unsafe { slice::from_raw_parts(ptr, num_kernel_symbols()) } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Retrieve the symbol corresponding to a virtual address, if any. +pub fn lookup_symbol(addr: Address) -> Option<&'static Symbol> { + kernel_symbols_slice() + .iter() + .find(|&i| i.contains(addr.as_usize())) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of symbols module. + #[kernel_test] + fn symbols_sanity() { + let first_sym = lookup_symbol(Address::new( + crate::common::is_aligned as *const usize as usize, + )) + .unwrap() + .name(); + + assert_eq!(first_sym, "libkernel::common::is_aligned"); + + let second_sym = lookup_symbol(Address::new(crate::version as *const usize as usize)) + .unwrap() + .name(); + + assert_eq!(second_sym, "libkernel::version"); + } +} diff --git a/17_kernel_symbols/kernel/src/synchronization.rs b/17_kernel_symbols/kernel/src/synchronization.rs new file mode 100644 index 000000000..5740b63e5 --- /dev/null +++ b/17_kernel_symbols/kernel/src/synchronization.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use crate::{exception, state}; + +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } +} diff --git a/17_kernel_symbols/kernel/src/time.rs b/17_kernel_symbols/kernel/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/17_kernel_symbols/kernel/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/17_kernel_symbols/kernel/tests/00_console_sanity.rb b/17_kernel_symbols/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/17_kernel_symbols/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/17_kernel_symbols/kernel/tests/00_console_sanity.rs b/17_kernel_symbols/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..682ea9b8a --- /dev/null +++ b/17_kernel_symbols/kernel/tests/00_console_sanity.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, memory, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/17_kernel_symbols/kernel/tests/01_timer_sanity.rs b/17_kernel_symbols/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..1581a02e0 --- /dev/null +++ b/17_kernel_symbols/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, memory, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/17_kernel_symbols/kernel/tests/02_exception_sync_page_fault.rs b/17_kernel_symbols/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..09d177981 --- /dev/null +++ b/17_kernel_symbols/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + info!("Writing to bottom of address space to address 1 GiB..."); + let big_addr: u64 = 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/17_kernel_symbols/kernel/tests/03_exception_restore_sanity.rb b/17_kernel_symbols/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/17_kernel_symbols/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/17_kernel_symbols/kernel/tests/03_exception_restore_sanity.rs b/17_kernel_symbols/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..1a3029112 --- /dev/null +++ b/17_kernel_symbols/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/17_kernel_symbols/kernel/tests/04_exception_irq_sanity.rs b/17_kernel_symbols/kernel/tests/04_exception_irq_sanity.rs new file mode 100644 index 000000000..fcace8979 --- /dev/null +++ b/17_kernel_symbols/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception, memory}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + memory::init(); + bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} diff --git a/17_kernel_symbols/kernel/tests/boot_test_string.rb b/17_kernel_symbols/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/17_kernel_symbols/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/17_kernel_symbols/kernel/tests/panic_exit_success/mod.rs b/17_kernel_symbols/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/17_kernel_symbols/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/17_kernel_symbols/kernel/tests/panic_wait_forever/mod.rs b/17_kernel_symbols/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/17_kernel_symbols/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/17_kernel_symbols/kernel_symbols.mk b/17_kernel_symbols/kernel_symbols.mk new file mode 100644 index 000000000..d38b7785a --- /dev/null +++ b/17_kernel_symbols/kernel_symbols.mk @@ -0,0 +1,117 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/format.mk +include ../common/docker.mk + +##-------------------------------------------------------------------------------------------------- +## Check for input variables that need be exported by the calling Makefile +##-------------------------------------------------------------------------------------------------- +ifndef KERNEL_SYMBOLS_TOOL_PATH +$(error KERNEL_SYMBOLS_TOOL_PATH is not set) +endif + +ifndef TARGET +$(error TARGET is not set) +endif + +ifndef KERNEL_SYMBOLS_INPUT_ELF +$(error KERNEL_SYMBOLS_INPUT_ELF is not set) +endif + +ifndef KERNEL_SYMBOLS_OUTPUT_ELF +$(error KERNEL_SYMBOLS_OUTPUT_ELF is not set) +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_SYMBOLS_MANIFEST = kernel_symbols/Cargo.toml +KERNEL_SYMBOLS_LINKER_SCRIPT = kernel_symbols/kernel_symbols.ld + +KERNEL_SYMBOLS_RS = $(KERNEL_SYMBOLS_INPUT_ELF)_symbols.rs +KERNEL_SYMBOLS_DEMANGLED_RS = $(shell pwd)/$(KERNEL_SYMBOLS_INPUT_ELF)_symbols_demangled.rs + +KERNEL_SYMBOLS_ELF = target/$(TARGET)/release/kernel_symbols +KERNEL_SYMBOLS_STRIPPED = target/$(TARGET)/release/kernel_symbols_stripped + +# Export for build.rs of kernel_symbols crate. +export KERNEL_SYMBOLS_DEMANGLED_RS + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +GET_SYMBOLS_SECTION_VIRT_ADDR = $(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) \ + --get_symbols_section_virt_addr $(KERNEL_SYMBOLS_OUTPUT_ELF) + +RUSTFLAGS = -C link-arg=--script=$(KERNEL_SYMBOLS_LINKER_SCRIPT) \ + -C link-arg=--section-start=.rodata=$$($(GET_SYMBOLS_SECTION_VIRT_ADDR)) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +COMPILER_ARGS = --target=$(TARGET) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_SYMBOLS_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_SYMBOLS_TOOL = ruby $(KERNEL_SYMBOLS_TOOL_PATH)/main.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all symbols measure_time_start measure_time_finish + +all: measure_time_start symbols measure_time_finish + +symbols: + @cp $(KERNEL_SYMBOLS_INPUT_ELF) $(KERNEL_SYMBOLS_OUTPUT_ELF) + + @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --gen_symbols $(KERNEL_SYMBOLS_OUTPUT_ELF) \ + $(KERNEL_SYMBOLS_RS) + + $(call color_progress_prefix, "Demangling") + @echo Symbol names + @cat $(KERNEL_SYMBOLS_RS) | rustfilt > $(KERNEL_SYMBOLS_DEMANGLED_RS) + + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + + $(call color_progress_prefix, "Stripping") + @echo Symbols ELF file + @$(OBJCOPY_CMD) $(KERNEL_SYMBOLS_ELF) $(KERNEL_SYMBOLS_STRIPPED) + + @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --patch_data $(KERNEL_SYMBOLS_OUTPUT_ELF) \ + $(KERNEL_SYMBOLS_STRIPPED) + +# Note: The following is the only _trivial_ way I could think of that works out of the box on both +# Linux and macOS. Since macOS does not have the %N nanosecond format string option, the +# resolution is restricted to whole seconds. +measure_time_start: + @date +%s > /tmp/kernel_symbols_start.date + +measure_time_finish: + @date +%s > /tmp/kernel_symbols_end.date + + $(call color_progress_prefix, "Finished") + @echo "in $$((`cat /tmp/kernel_symbols_end.date` - `cat /tmp/kernel_symbols_start.date`)).0s" + + @rm /tmp/kernel_symbols_end.date /tmp/kernel_symbols_start.date diff --git a/17_kernel_symbols/kernel_symbols/Cargo.toml b/17_kernel_symbols/kernel_symbols/Cargo.toml new file mode 100644 index 000000000..3407aa7e1 --- /dev/null +++ b/17_kernel_symbols/kernel_symbols/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "kernel_symbols" +version = "0.1.0" +edition = "2021" + +[features] +default = [] +generated_symbols_available = [] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +debug-symbol-types = { path = "../libraries/debug-symbol-types" } diff --git a/17_kernel_symbols/kernel_symbols/build.rs b/17_kernel_symbols/kernel_symbols/build.rs new file mode 100644 index 000000000..5062df444 --- /dev/null +++ b/17_kernel_symbols/kernel_symbols/build.rs @@ -0,0 +1,14 @@ +use std::{env, path::Path}; + +fn main() { + if let Ok(path) = env::var("KERNEL_SYMBOLS_DEMANGLED_RS") { + if Path::new(&path).exists() { + println!("cargo:rustc-cfg=feature=\"generated_symbols_available\"") + } + } + + println!( + "cargo:rerun-if-changed={}", + Path::new("kernel_symbols.ld").display() + ); +} diff --git a/17_kernel_symbols/kernel_symbols/kernel_symbols.ld b/17_kernel_symbols/kernel_symbols/kernel_symbols.ld new file mode 100644 index 000000000..0625f0086 --- /dev/null +++ b/17_kernel_symbols/kernel_symbols/kernel_symbols.ld @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2022 Andre Richter + */ + +SECTIONS +{ + .rodata : { + ASSERT(. > 0xffffffff00000000, "Expected higher half address") + + KEEP(*(.rodata.symbol_desc*)) + . = ALIGN(8); + *(.rodata*) + } +} diff --git a/17_kernel_symbols/kernel_symbols/src/main.rs b/17_kernel_symbols/kernel_symbols/src/main.rs new file mode 100644 index 000000000..38ce18f8f --- /dev/null +++ b/17_kernel_symbols/kernel_symbols/src/main.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Generation of kernel symbols. + +#![no_std] +#![no_main] + +#[cfg(feature = "generated_symbols_available")] +include!(env!("KERNEL_SYMBOLS_DEMANGLED_RS")); + +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unimplemented!() +} diff --git a/17_kernel_symbols/libraries/debug-symbol-types/Cargo.toml b/17_kernel_symbols/libraries/debug-symbol-types/Cargo.toml new file mode 100644 index 000000000..e5b1fd1f5 --- /dev/null +++ b/17_kernel_symbols/libraries/debug-symbol-types/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "debug-symbol-types" +version = "0.1.0" +edition = "2021" diff --git a/17_kernel_symbols/libraries/debug-symbol-types/src/lib.rs b/17_kernel_symbols/libraries/debug-symbol-types/src/lib.rs new file mode 100644 index 000000000..81c897bfa --- /dev/null +++ b/17_kernel_symbols/libraries/debug-symbol-types/src/lib.rs @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Types for implementing debug symbol support. + +#![no_std] + +use core::ops::Range; + +/// A symbol containing a size. +#[repr(C)] +#[derive(Clone)] +pub struct Symbol { + addr_range: Range, + name: &'static str, +} + +impl Symbol { + /// Create an instance. + pub const fn new(start: usize, size: usize, name: &'static str) -> Symbol { + Symbol { + addr_range: Range { + start, + end: start + size, + }, + name, + } + } + + /// Returns true if addr is contained in the range. + pub fn contains(&self, addr: usize) -> bool { + self.addr_range.contains(&addr) + } + + /// Returns the symbol's name. + pub fn name(&self) -> &'static str { + self.name + } + + /// Returns the symbol's size. + pub fn size(&self) -> usize { + self.addr_range.end - self.addr_range.start + } +} diff --git a/17_kernel_symbols/libraries/test-macros/Cargo.toml b/17_kernel_symbols/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/17_kernel_symbols/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/17_kernel_symbols/libraries/test-macros/src/lib.rs b/17_kernel_symbols/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/17_kernel_symbols/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/17_kernel_symbols/libraries/test-types/Cargo.toml b/17_kernel_symbols/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/17_kernel_symbols/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/17_kernel_symbols/libraries/test-types/src/lib.rs b/17_kernel_symbols/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/17_kernel_symbols/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/17_kernel_symbols/tools/kernel_symbols_tool/cmds.rb b/17_kernel_symbols/tools/kernel_symbols_tool/cmds.rb new file mode 100644 index 000000000..c43acb24c --- /dev/null +++ b/17_kernel_symbols/tools/kernel_symbols_tool/cmds.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +def generate_symbols(kernel_elf, output_file) + File.open(output_file, 'w') do |file| + header = <<~HEREDOC + use debug_symbol_types::Symbol; + + # [no_mangle] + # [link_section = ".rodata.symbol_desc"] + static KERNEL_SYMBOLS: [Symbol; #{kernel_elf.num_symbols}] = [ + HEREDOC + + file.write(header) + kernel_elf.symbols.each do |sym| + value = sym.header.st_value + size = sym.header.st_size + name = sym.name + + file.write(" Symbol::new(#{value}, #{size}, \"#{name}\"),\n") + end + file.write("];\n") + end +end + +def get_symbols_section_virt_addr(kernel_elf) + kernel_elf.kernel_symbols_section_virt_addr +end + +def patch_symbol_data(kernel_elf, symbols_blob_path) + symbols_blob = File.binread(symbols_blob_path) + + raise if symbols_blob.size > kernel_elf.kernel_symbols_section_size + + File.binwrite(kernel_elf.path, File.binread(symbols_blob_path), + kernel_elf.kernel_symbols_section_offset_in_file) +end + +def patch_num_symbols(kernel_elf) + num_packed = [kernel_elf.num_symbols].pack('Q<*') # "Q" == uint64_t, "<" == little endian + File.binwrite(kernel_elf.path, num_packed, kernel_elf.num_kernel_symbols_offset_in_file) +end diff --git a/17_kernel_symbols/tools/kernel_symbols_tool/kernel_elf.rb b/17_kernel_symbols/tools/kernel_symbols_tool/kernel_elf.rb new file mode 100644 index 000000000..32b5460aa --- /dev/null +++ b/17_kernel_symbols/tools/kernel_symbols_tool/kernel_elf.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + attr_reader :path + + def initialize(kernel_elf_path, kernel_symbols_section, num_kernel_symbols) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + + @path = kernel_elf_path + fetch_values(kernel_symbols_section, num_kernel_symbols) + end + + private + + def fetch_values(kernel_symbols_section, num_kernel_symbols) + sym = @symtab_section.symbol_by_name(num_kernel_symbols) + raise "Symbol \"#{num_kernel_symbols}\" not found" if sym.nil? + + @num_kernel_symbols = sym + + section = @elf.section_by_name(kernel_symbols_section) + raise "Section \"#{kernel_symbols_section}\" not found" if section.nil? + + @kernel_symbols_section = section + end + + def num_kernel_symbols_virt_addr + @num_kernel_symbols.header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + public + + def symbols + non_zero_symbols = @symtab_section.symbols.reject { |sym| sym.header.st_size.zero? } + non_zero_symbols.sort_by { |sym| sym.header.st_value } + end + + def num_symbols + symbols.size + end + + def kernel_symbols_section_virt_addr + @kernel_symbols_section.header.sh_addr.to_i + end + + def kernel_symbols_section_size + @kernel_symbols_section.header.sh_size.to_i + end + + def kernel_symbols_section_offset_in_file + virt_addr_to_file_offset(kernel_symbols_section_virt_addr) + end + + def num_kernel_symbols_offset_in_file + virt_addr_to_file_offset(num_kernel_symbols_virt_addr) + end +end diff --git a/17_kernel_symbols/tools/kernel_symbols_tool/main.rb b/17_kernel_symbols/tools/kernel_symbols_tool/main.rb new file mode 100755 index 000000000..899f96464 --- /dev/null +++ b/17_kernel_symbols/tools/kernel_symbols_tool/main.rb @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'kernel_elf' +require_relative 'cmds' + +KERNEL_SYMBOLS_SECTION = '.kernel_symbols' +NUM_KERNEL_SYMBOLS = 'NUM_KERNEL_SYMBOLS' + +cmd = ARGV[0] + +kernel_elf_path = ARGV[1] +kernel_elf = KernelELF.new(kernel_elf_path, KERNEL_SYMBOLS_SECTION, NUM_KERNEL_SYMBOLS) + +case cmd +when '--gen_symbols' + output_file = ARGV[2] + + print 'Generating'.rjust(12).green.bold + puts ' Symbols source file' + + generate_symbols(kernel_elf, output_file) +when '--get_symbols_section_virt_addr' + addr = get_symbols_section_virt_addr(kernel_elf) + + puts "0x#{addr.to_s(16)}" +when '--patch_data' + symbols_blob_path = ARGV[2] + num_symbols = kernel_elf.num_symbols + + print 'Patching'.rjust(12).green.bold + puts " Symbols blob and number of symbols (#{num_symbols}) into ELF" + + patch_symbol_data(kernel_elf, symbols_blob_path) + patch_num_symbols(kernel_elf) +else + raise +end diff --git a/17_kernel_symbols/tools/translation_table_tool/arch.rb b/17_kernel_symbols/tools/translation_table_tool/arch.rb new file mode 100644 index 000000000..053cac194 --- /dev/null +++ b/17_kernel_symbols/tools/translation_table_tool/arch.rb @@ -0,0 +1,314 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Bitfield manipulation. +class BitField + def initialize + @value = 0 + end + + def self.attr_bitfield(name, offset, num_bits) + define_method("#{name}=") do |bits| + mask = (2**num_bits) - 1 + + raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? + + # Clear bitfield + @value &= ~(mask << offset) + + # Set it + @value |= (bits << offset) + end + end + + def to_i + @value + end + + def size_in_byte + 8 + end +end + +# An array class that knows its memory location. +class CArray < Array + attr_reader :phys_start_addr + + def initialize(phys_start_addr, size, &block) + @phys_start_addr = phys_start_addr + + super(size, &block) + end + + def size_in_byte + inject(0) { |sum, n| sum + n.size_in_byte } + end +end + +#--------------------------------------------------------------------------------------------------- +# Arch:: +#--------------------------------------------------------------------------------------------------- +module Arch +#--------------------------------------------------------------------------------------------------- +# Arch::ARMv8 +#--------------------------------------------------------------------------------------------------- +module ARMv8 +# ARMv8 Table Descriptor. +class Stage1TableDescriptor < BitField + module NextLevelTableAddr + OFFSET = 16 + NUMBITS = 32 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + BLOCK = 0 + TABLE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def next_level_table_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__next_level_table_addr = addr + end + + private :__next_level_table_addr= +end + +# ARMv8 level 3 page descriptor. +class Stage1PageDescriptor < BitField + module UXN + OFFSET = 54 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module PXN + OFFSET = 53 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module OutputAddr + OFFSET = 16 + NUMBITS = 32 + end + + module AF + OFFSET = 10 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module SH + OFFSET = 8 + NUMBITS = 2 + + INNER_SHAREABLE = 0b11 + end + + module AP + OFFSET = 6 + NUMBITS = 2 + + RW_EL1 = 0b00 + RO_EL1 = 0b10 + end + + module AttrIndx + OFFSET = 2 + NUMBITS = 3 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + RESERVED_INVALID = 0 + PAGE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) + attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) + attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) + attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) + attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) + attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) + attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def output_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__output_addr = addr + end + + private :__output_addr= +end + +# Translation table representing the structure defined in translation_table.rs. +class TranslationTable + module MAIR + NORMAL = 1 + end + + def initialize + do_sanity_checks + + num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT + + @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) + + @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte + @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) + + populate_lvl2_entries + end + + def map_at(virt_region, phys_region, attributes) + return if virt_region.empty? + + raise if virt_region.size != phys_region.size + raise if phys_region.last > BSP.phys_addr_space_end_page + + virt_region.zip(phys_region).each do |virt_page, phys_page| + desc = page_descriptor_from(virt_page) + set_lvl3_entry(desc, phys_page, attributes) + end + end + + def to_binary + data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) + data.pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr_binary + [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr + @lvl2_phys_start_addr + end + + private + + def do_sanity_checks + raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE + raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? + end + + def new_lvl3(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + temp = CArray.new(start_addr, 8192) do + Stage1PageDescriptor.new + end + start_addr += temp.size_in_byte + + temp + end + end + + def new_lvl2(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + Stage1TableDescriptor.new + end + end + + def populate_lvl2_entries + @lvl2.each_with_index do |descriptor, i| + descriptor.next_level_table_addr = @lvl3[i].phys_start_addr + descriptor.type = Stage1TableDescriptor::Type::TABLE + descriptor.valid = Stage1TableDescriptor::Valid::TRUE + end + end + + def lvl2_lvl3_index_from(addr) + addr -= BSP.kernel_virt_start_addr + + lvl2_index = addr >> Granule512MiB::SHIFT + lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT + + raise unless lvl2_index < @lvl2.size + + [lvl2_index, lvl3_index] + end + + def page_descriptor_from(virt_addr) + lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) + + @lvl3[lvl2_index][lvl3_index] + end + + # rubocop:disable Metrics/MethodLength + def set_attributes(desc, attributes) + case attributes.mem_attributes + when :CacheableDRAM + desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE + desc.attr_indx = MAIR::NORMAL + else + raise 'Invalid input' + end + + desc.ap = case attributes.acc_perms + when :ReadOnly + Stage1PageDescriptor::AP::RO_EL1 + when :ReadWrite + Stage1PageDescriptor::AP::RW_EL1 + else + raise 'Invalid input' + + end + + desc.pxn = if attributes.execute_never + Stage1PageDescriptor::PXN::TRUE + else + Stage1PageDescriptor::PXN::FALSE + end + + desc.uxn = Stage1PageDescriptor::UXN::TRUE + end + # rubocop:enable Metrics/MethodLength + + def set_lvl3_entry(desc, output_addr, attributes) + desc.output_addr = output_addr + desc.af = Stage1PageDescriptor::AF::TRUE + desc.type = Stage1PageDescriptor::Type::PAGE + desc.valid = Stage1PageDescriptor::Valid::TRUE + + set_attributes(desc, attributes) + end +end +end +end diff --git a/17_kernel_symbols/tools/translation_table_tool/bsp.rb b/17_kernel_symbols/tools/translation_table_tool/bsp.rb new file mode 100644 index 000000000..93bcedd94 --- /dev/null +++ b/17_kernel_symbols/tools/translation_table_tool/bsp.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Raspberry Pi 3 + 4 +class RaspberryPi + attr_reader :kernel_granule, :kernel_virt_addr_space_size, :kernel_virt_start_addr + + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + + def initialize + @kernel_granule = Granule64KiB + + @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') + @kernel_virt_start_addr = KERNEL_ELF.symbol_value('__kernel_virt_start_addr') + + @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') + @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( + 'PHYS_KERNEL_TABLES_BASE_ADDR' + ) + end + + def phys_addr_of_kernel_tables + KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) + end + + def kernel_tables_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) + end + + def phys_kernel_tables_base_addr_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) + end + + def phys_addr_space_end_page + x = MEMORY_SRC.grep(/pub const END/) + x = case BSP_TYPE + when :rpi3 + x[0] + when :rpi4 + x[1] + else + raise + end + + x.scan(/\d+/).join.to_i(16) + end +end diff --git a/17_kernel_symbols/tools/translation_table_tool/generic.rb b/17_kernel_symbols/tools/translation_table_tool/generic.rb new file mode 100644 index 000000000..743840e00 --- /dev/null +++ b/17_kernel_symbols/tools/translation_table_tool/generic.rb @@ -0,0 +1,179 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +module Granule64KiB + SIZE = 64 * 1024 + SHIFT = Math.log2(SIZE).to_i +end + +module Granule512MiB + SIZE = 512 * 1024 * 1024 + SHIFT = Math.log2(SIZE).to_i + MASK = SIZE - 1 +end + +# Monkey-patch Integer with some helper functions. +class Integer + def power_of_two? + self[0].zero? + end + + def aligned?(alignment) + raise unless alignment.power_of_two? + + (self & (alignment - 1)).zero? + end + + def align_up(alignment) + raise unless alignment.power_of_two? + + (self + alignment - 1) & ~(alignment - 1) + end + + def to_hex_underscore(with_leading_zeros: false) + fmt = with_leading_zeros ? '%016x' : '%x' + value = format(fmt, self).to_s.reverse.scan(/.{4}|.+/).join('_').reverse + + format('0x%s', value) + end +end + +# An array where each value is the start address of a Page. +class MemoryRegion < Array + def initialize(start_addr, size, granule_size) + raise unless start_addr.aligned?(granule_size) + raise unless size.positive? + raise unless (size % granule_size).zero? + + num_pages = size / granule_size + super(num_pages) do |i| + (i * granule_size) + start_addr + end + end +end + +# Collection of memory attributes. +class AttributeFields + attr_reader :mem_attributes, :acc_perms, :execute_never + + def initialize(mem_attributes, acc_perms, execute_never) + @mem_attributes = mem_attributes + @acc_perms = acc_perms + @execute_never = execute_never + end + + def to_s + x = case @mem_attributes + when :CacheableDRAM + 'C' + else + '?' + end + + y = case @acc_perms + when :ReadWrite + 'RW' + when :ReadOnly + 'RO' + else + '??' + end + + z = @execute_never ? 'XN' : 'X ' + + "#{x} #{y} #{z}" + end +end + +# A container that describes a virt-to-phys region mapping. +class MappingDescriptor + @max_section_name_length = 'Sections'.length + + class << self + attr_accessor :max_section_name_length + + def update_max_section_name_length(length) + @max_section_name_length = [@max_section_name_length, length].max + end + end + + attr_reader :name, :virt_region, :phys_region, :attributes + + def initialize(name, virt_region, phys_region, attributes) + @name = name + @virt_region = virt_region + @phys_region = phys_region + @attributes = attributes + end + + def to_s + name = @name.ljust(self.class.max_section_name_length) + virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) + phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) + size = ((@virt_region.size * 65_536) / 1024).to_s.rjust(3) + + "#{name} | #{virt_start} | #{phys_start} | #{size} KiB | #{@attributes}" + end + + def self.print_divider + print ' ' + print '-' * max_section_name_length + puts '--------------------------------------------------------------------' + end + + def self.print_header + print_divider + print ' ' + print 'Sections'.center(max_section_name_length) + print ' ' + print 'Virt Start Addr'.center(21) + print ' ' + print 'Phys Start Addr'.center(21) + print ' ' + print 'Size'.center(7) + print ' ' + print 'Attr'.center(7) + puts + print_divider + end +end + +def kernel_map_binary + mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors + + # Generate_mapping_descriptors updates the header being printed with this call. So it must come + # afterwards. + MappingDescriptor.print_header + + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' + puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end + + MappingDescriptor.print_divider +end + +def kernel_patch_tables(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel table struct at ELF file offset ' + puts BSP.kernel_tables_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.to_binary, BSP.kernel_tables_offset_in_file) +end + +def kernel_patch_base_addr(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel tables physical base address start argument to value ' + print TRANSLATION_TABLES.phys_tables_base_addr.to_hex_underscore + print ' at ELF file offset ' + puts BSP.phys_kernel_tables_base_addr_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.phys_tables_base_addr_binary, + BSP.phys_kernel_tables_base_addr_offset_in_file) +end diff --git a/17_kernel_symbols/tools/translation_table_tool/kernel_elf.rb b/17_kernel_symbols/tools/translation_table_tool/kernel_elf.rb new file mode 100644 index 000000000..5ba78d9df --- /dev/null +++ b/17_kernel_symbols/tools/translation_table_tool/kernel_elf.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + SECTION_FLAG_ALLOC = 2 + + def initialize(kernel_elf_path) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + end + + def machine + @elf.machine.to_sym + end + + def symbol_value(symbol_name) + @symtab_section.symbol_by_name(symbol_name).header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_to_phys(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + translation_offset = segment.header.p_vaddr - segment.header.p_paddr + + virt_addr - translation_offset + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + def sections_in_segment(segment) + head = segment.mem_head + tail = segment.mem_tail + + sections = @elf.each_sections.select do |section| + file_offset = section.header.sh_addr + flags = section.header.sh_flags + + file_offset >= head && file_offset < tail && (flags & SECTION_FLAG_ALLOC != 0) + end + + sections.map(&:name).join(' ') + end + + def select_load_segments + @elf.each_segments.select do |segment| + segment.instance_of?(ELFTools::Segments::LoadSegment) + end + end + + def segment_get_acc_perms(segment) + if segment.readable? && segment.writable? + :ReadWrite + elsif segment.readable? + :ReadOnly + else + :Invalid + end + end + + def update_max_section_name_length(descriptors) + MappingDescriptor.update_max_section_name_length(descriptors.map { |i| i.name.size }.max) + end + + def generate_mapping_descriptors + descriptors = select_load_segments.map do |segment| + # Assume each segment is page aligned. + size = segment.mem_size.align_up(BSP.kernel_granule::SIZE) + virt_start_addr = segment.header.p_vaddr + phys_start_addr = segment.header.p_paddr + acc_perms = segment_get_acc_perms(segment) + execute_never = !segment.executable? + section_names = sections_in_segment(segment) + + virt_region = MemoryRegion.new(virt_start_addr, size, BSP.kernel_granule::SIZE) + phys_region = MemoryRegion.new(phys_start_addr, size, BSP.kernel_granule::SIZE) + attributes = AttributeFields.new(:CacheableDRAM, acc_perms, execute_never) + + MappingDescriptor.new(section_names, virt_region, phys_region, attributes) + end + + update_max_section_name_length(descriptors) + descriptors + end +end diff --git a/17_kernel_symbols/tools/translation_table_tool/main.rb b/17_kernel_symbols/tools/translation_table_tool/main.rb new file mode 100755 index 000000000..22ab24fd5 --- /dev/null +++ b/17_kernel_symbols/tools/translation_table_tool/main.rb @@ -0,0 +1,46 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'generic' +require_relative 'kernel_elf' +require_relative 'bsp' +require_relative 'arch' + +BSP_TYPE = ARGV[0].to_sym +kernel_elf_path = ARGV[1] + +start = Time.now + +KERNEL_ELF = KernelELF.new(kernel_elf_path) + +BSP = case BSP_TYPE + when :rpi3, :rpi4 + RaspberryPi.new + else + raise + end + +TRANSLATION_TABLES = case KERNEL_ELF.machine + when :AArch64 + Arch::ARMv8::TranslationTable.new + else + raise + end + +kernel_map_binary +kernel_patch_tables(kernel_elf_path) +kernel_patch_base_addr(kernel_elf_path) + +elapsed = Time.now - start + +print 'Finished'.rjust(12).green.bold +puts " in #{elapsed.round(2)}s" diff --git a/18_backtrace/.cargo/config.toml b/18_backtrace/.cargo/config.toml new file mode 100644 index 000000000..e34764853 --- /dev/null +++ b/18_backtrace/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.'cfg(target_os = "none")'] +runner = "target/kernel_test_runner.sh" diff --git a/18_backtrace/.vscode/settings.json b/18_backtrace/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/18_backtrace/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/18_backtrace/Cargo.lock b/18_backtrace/Cargo.lock new file mode 100644 index 000000000..701f10f18 --- /dev/null +++ b/18_backtrace/Cargo.lock @@ -0,0 +1,96 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "debug-symbol-types" +version = "0.1.0" + +[[package]] +name = "kernel_symbols" +version = "0.1.0" +dependencies = [ + "debug-symbol-types", +] + +[[package]] +name = "mingo" +version = "0.18.0" +dependencies = [ + "aarch64-cpu", + "debug-symbol-types", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/18_backtrace/Cargo.toml b/18_backtrace/Cargo.toml new file mode 100644 index 000000000..38eeb1165 --- /dev/null +++ b/18_backtrace/Cargo.toml @@ -0,0 +1,11 @@ +[workspace] + +members = [ + "libraries/*", + "kernel", + "kernel_symbols" +] + +[profile.release] +lto = true +debug = true diff --git a/18_backtrace/Makefile b/18_backtrace/Makefile new file mode 100644 index 000000000..7edf4edf6 --- /dev/null +++ b/18_backtrace/Makefile @@ -0,0 +1,388 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -C force-frame-pointers +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -C force-frame-pointers +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF_RAW = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_RAW_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Translation tables +##------------------------------------------------------------------------------ +TT_TOOL_PATH = tools/translation_table_tool + +KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables +KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) + +##------------------------------------------------------------------------------ +## Kernel symbols +##------------------------------------------------------------------------------ +export KERNEL_SYMBOLS_TOOL_PATH = tools/kernel_symbols_tool + +KERNEL_ELF_TTABLES_SYMS = target/$(TARGET)/release/kernel+ttables+symbols + +# Unlike with KERNEL_ELF_RAW, we are not relying on dep-info here. One of the reasons being that the +# name of the generated symbols file varies between runs, which can cause confusion. +KERNEL_ELF_TTABLES_SYMS_DEPS = $(KERNEL_ELF_TTABLES) \ + $(wildcard kernel_symbols/*) \ + $(wildcard $(KERNEL_SYMBOLS_TOOL_PATH)/*) + +export TARGET +export KERNEL_SYMBOLS_INPUT_ELF = $(KERNEL_ELF_TTABLES) +export KERNEL_SYMBOLS_OUTPUT_ELF = $(KERNEL_ELF_TTABLES_SYMS) + +KERNEL_ELF = $(KERNEL_ELF_TTABLES_SYMS) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +# build-std can be skipped for helper commands that do not rely on correct stack frames and other +# custom compiler options. This results in a huge speedup. +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -Z build-std=core --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) -Z build-std=core --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Precompute the kernel translation tables and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) + $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") + @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) + +##------------------------------------------------------------------------------ +## Generate kernel symbols and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES_SYMS): $(KERNEL_ELF_TTABLES_SYMS_DEPS) + $(call color_header, "Generating kernel symbols and patching kernel ELF") + @$(MAKE) --no-print-directory -f kernel_symbols.mk + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF_TTABLES_SYMS) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES_SYMS) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: clean + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb-opt0: RUSTC_MISC_ARGS += -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_ELF_SYMS="$${TEST_ELF}_syms" + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null + + # This overrides the two ENV variables. The other ENV variables that are required as input for + # the .mk file are set already because they are exported by this Makefile and this script is + # started by the same. + KERNEL_SYMBOLS_INPUT_ELF=$$TEST_ELF \ + KERNEL_SYMBOLS_OUTPUT_ELF=$$TEST_ELF_SYMS \ + $(MAKE) --no-print-directory -f kernel_symbols.mk > /dev/null 2>&1 + + $(OBJCOPY_CMD) $$TEST_ELF_SYMS $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/18_backtrace/README.md b/18_backtrace/README.md new file mode 100644 index 000000000..00a156d7b --- /dev/null +++ b/18_backtrace/README.md @@ -0,0 +1,1320 @@ +# Tutorial 18 - Backtracing + +## tl;dr + +- Support for [`backtracing`] is implemented into the kernel. + +```console +[ 0.002782] Writing to bottom of address space to address 1 GiB... +[ 0.004623] Kernel panic! + +Panic location: + File 'kernel/src/_arch/aarch64/exception.rs', line 59, column 5 + +[...] + +Backtrace: + ---------------------------------------------------------------------------------------------- + Address Function containing address + ---------------------------------------------------------------------------------------------- + 1. ffffffffc0005560 | libkernel::panic_wait::_panic_print + 2. ffffffffc00054a0 | rust_begin_unwind + 3. ffffffffc0002950 | core::panicking::panic_fmt + 4. ffffffffc0004898 | current_elx_synchronous + 5. ffffffffc0000a74 | __vector_current_elx_synchronous + 6. ffffffffc000111c | kernel_init + ---------------------------------------------------------------------------------------------- +``` + +[`backtracing`]: https://en.wikipedia.org/wiki/Stack_trace + +## Table of Contents + +- [Introduction](#introduction) +- [Implementation](#implementation) + - [Chasing Frames](#chasing-frames) + - [Compiler Changes](#compiler-changes) + - [Supporting Changes](#supporting-changes) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +Since the kernel gained support for looking up `symbol names` in the previous tutorial, it is now +possible to implement support for printing meaningful backtraces (also called `stack traces`). The +primary use-case will be printing backtraces during a `panic`, which will ease debugging. This is a +good time to add this feature, since some of the upcoming tutorials will cover complex topics and +code changes, so that this will come in handy during development. + +## Implementation + +Since backtracing is a scheme that is usually defined in the [`calling-convention`], and therefore +tightly coupled to the `processor architecture `, the heart of the backtracing code will live in the +`_arch` folder. What can be shared between different architectures is the formatting and printing +part. Hence, the code will be organized as follows: + +[`calling-convention`]: https://en.wikipedia.org/wiki/Calling_convention + +- `src/backtrace.rs` makes a generic definition of a `BacktraceItem`. It also provides code that + uses an `Iterator` to format and print the backtrace. +- `src/__arch_name__/backtrace.rs` contains the code that generates the actual iterator. + +Here is the definition of `BacktraceItem`: + +```rust +pub enum BacktraceItem { + InvalidFramePointer(Address), + InvalidLink(Address), + Link(Address), +} +``` + +In summary, it has two error cases and one valid case. This will become clearer in a minute when we +look at what a `stack frame` and a `frame pointer` is. + +### Chasing Frames + +For `AArch64`, we need to consult the [Procedure Call Standard for the Arm® 64-bit Architecture] +(`AAPCS64`). It has the following to say: + +> Conforming code shall construct a *linked list* of stack-frames. Each frame shall link to the +> frame of its caller by means of a frame record of two 64-bit values on the stack (independent of +> the data model). The frame record for the innermost frame (belonging to the most recent routine +> invocation) shall be pointed to by the frame pointer register (FP). The lowest addressed +> double-word shall point to the previous frame record and the highest addressed double-word shall +> contain the value passed in LR on entry to the current function [...]. The location of the frame +> record within a stack frame is not specified. + +[Procedure Call Standard for the Arm® 64-bit Architecture]: https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst + +The nature of the `linked list` becomes a bit clearer when we look into the corresponding section in +the [ARM Cortex-A Series Programmer’s Guide for ARMv8-A] as well. Here are text and picture +snippets: + +> An AAPC64 stack frame shown in Figure 9-2. The frame pointer (X29) should point to the previous +> frame pointer saved on stack, with the saved LR (X30) stored after it. The final frame pointer in +> the chain should be set to 0. The Stack Pointer must always be aligned on a 16 byte boundary. + +[ARM Cortex-A Series Programmer’s Guide for ARMv8-A]: https://developer.arm.com/documentation/den0024/latest/ + +

+ +

+ +Hence, we can define the following struct in `src/__arch_name__/backtrace.rs` for the stack frame +record: + +```rust +#[repr(C)] +struct StackFrameRecord<'a> { + previous_record: Option<&'a StackFrameRecord<'a>>, + link: Address, +} +``` + +The interesting part is the `previous_record` member. We learned from the two documents which we +inspected above that the lowest addressed double-word is either: + +- Zero. +- Or pointing to the previous stack frame record. + +Thanks to Rust's null pointer optimization [[1]][[2]], this allows us to conveniently type this as +an `Option<&StackFrameRecord>`. So whenever we inspect `previous_record` and observe it to be +`None`, we know that we've reached the end of the backtrace. + +[1]: https://doc.rust-lang.org/std/option/#representation +[2]: https://stackoverflow.com/a/46557737 + +The start of the backtrace is trivially accessed through `x29` (aka the `Frame Pointer Register`). +This is used to generate a `StackFrameIterator`: + +```rust +struct StackFrameRecordIterator<'a> { + cur: &'a StackFrameRecord<'a>, +} + +/// [...] + +fn stack_frame_record_iterator<'a>() -> Option> { + let fp = Address::::new(FP.get() as usize); + if !fp.is_valid_stack_addr() { + return None; + } + + Some(StackFrameRecordIterator { + cur: unsafe { &*(fp.as_usize() as *const _) }, + }) +} +``` + +Although it should be guaranteed by the compiler (and any hand-written assembly) that `x29` points +to a valid stack address, it makes sense to double-check this before generating a reference. There +is always a chance that corruption happens. The implementation of the iterator itself does this +sanity check as well whenever the iterator is advanced. Additionally, it is also checked whether the +`link` address points to a valid `code` section in the kernel before the address is passed on to +the caller of the iterator: + +```rust +impl<'a> Iterator for StackFrameRecordIterator<'a> { + type Item = BacktraceItem; + + fn next(&mut self) -> Option { + static ABORT_FRAME: StackFrameRecord = StackFrameRecord { + previous_record: None, + link: Address::new(0), + }; + + // If previous is None, this is the root frame, so iteration will stop here. + let previous = self.cur.previous_record?; + + // Need to abort if the pointer to the previous frame record is invalid. + let prev_addr = Address::::new(previous as *const _ as usize); + if !prev_addr.is_valid_stack_addr() { + // This allows to return the error and then stop on the next iteration. + self.cur = &ABORT_FRAME; + return Some(BacktraceItem::InvalidFramePointer(prev_addr)); + } + + let ret = if !self.cur.link.is_valid_code_addr() { + Some(BacktraceItem::InvalidLink(self.cur.link)) + } else { + // The link points to the instruction to be executed _after_ returning from a branch. + // However, we want to show the instruction that caused the branch, so subtract by one + // instruction. + // + // This might be called from panic!, so it must not panic itself on the subtraction. + let link = if self.cur.link >= Address::new(4) { + self.cur.link - 4 + } else { + self.cur.link + }; + + Some(BacktraceItem::Link(link)) + }; + + // Advance the iterator. + self.cur = previous; + + ret + } +} +``` + +This already was the gist of the architectural part of the implementation! In the generic part, +where the backtrace is printed, the address returned in `BacktraceItem::Link` is additionally used +to look up the corresponding `symbol`, so that this is conveniently printed together: + +```rust +match backtrace_res { + + // omitted + + BacktraceItem::Link(addr) => { + fmt_res = writeln!( + f, + " {:>2}. {:016x} | {:<50}", + i + 1, + addr.as_usize(), + match symbols::lookup_symbol(addr) { + Some(sym) => sym.name(), + _ => "Symbol not found", + } + ) + } +}; +``` + +Finally, we add printing of a backtrace to `panic!`: + +```rust +println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + backtrace::Backtrace +); +``` + +### Compiler Changes + +By default, the `aarch64-unknown-none*` targets *do not* guarantee that a stack frame record is +generated on each function call. Without, the backtracing code will not work. Fortunately, +generation can be forced by modifying the `rustc codegen options`. We add the following to the +`Makefile`: + +```makefile +ifeq ($(BSP),rpi3) + + # omitted + + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -C force-frame-pointers +``` + +But there is more! Until now, when we compiled the kernel, cargo was using a **precompiled** version +of the `Rust core library` that comes with rustup whenever a target is added. This is usually very +beneficial in terms of speeding up compilation. Unfortunately, the precompiled version was not +compiled with `-C force-frame-pointers` either. This can be solved using cargo's [`build-std` +feature]. We set it in the Makefile so that cargo also compiles the core library using our compiler +settings, which means we get the frame records thanks to `-C force-frame-pointers` for any core +library functions as well. + +```Makefile +# build-std can be skipped for helper commands that do not rely on correct stack frames and other +# custom compiler options. This results in a huge speedup. +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -Z build-std=core --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) -Z build-std=core --manifest-path $(KERNEL_MANIFEST) +``` + +[`build-std` feature]: https://doc.rust-lang.org/cargo/reference/unstable.html#build-std + +### Supporting Changes + +There's a couple of changes not covered in this tutorial text, but the reader should ideally skim +through them: + +- [`src/_arch/aarch64/exception.s`](`kernel/src/_arch/aarch64/exception.s`) adds some tricky code to + generate a stack frame record on exception entry. The file includes elaborate comments that can be + inspected. +- [`src/_arch/aarch64/cpu/boot.rs`](`kernel/src/_arch/aarch64/cpu/boot.rs`) adds some code that + ensures that `kernel_init()` becomes the root of the backtrace (meaning its is ensured that + `previous_frame` will be zero for `kernel_init()`'s frame record). +- In `$ROOT/Cargo.toml`, `debug = true` has been set, which ensures that the kernel ELF includes the + maximum amount of debug information. Please note that this does *not* change anything for the + kernel at runtime. However, it will allow to dig even deeper on an address that has been reported + by a kernel backtrace. For example, using the `addr2line` tool. The following two snippets show + what `addr2line` reports when the debug flag is not or is set, respectively. + +```console +$ # debug = false +$ addr2line -p -f -s -i -e target/aarch64-unknown-none-softfloat/release/kernel+ttables+symbols 0xffffffffc0001da8 | rustfilt +kernel::kernel_main at kernel.c562062a-cgu.1:? +``` + +```console +$ # debug = true +$ addr2line -p -f -s -i -e target/aarch64-unknown-none-softfloat/release/kernel+ttables+symbols 0xffffffffc0001da8 | rustfilt +libkernel::memory::mmu::mapping_record::MappingRecord::print at mapping_record.rs:136 + (inlined by) libkernel::memory::mmu::mapping_record::kernel_print::{{closure}} at mapping_record.rs:232 + (inlined by) as libkernel::synchronization::interface::ReadWriteEx>::read at synchronization.rs:139 + (inlined by) libkernel::memory::mmu::mapping_record::kernel_print at mapping_record.rs:232 + (inlined by) libkernel::memory::mmu::kernel_print_mappings at mmu.rs:269 + (inlined by) kernel::kernel_main at main.rs:84 +``` + +## Test it + +Three tests were added that check the sanity of the backtracing code. Also, any previous tests that +print a `panic` will now also include a backtrace. For example, `02_exception_sync_page_fault.rs`: + +```console +$ TEST=02_exception_sync_page_fault make test_integration +[...] + ------------------------------------------------------------------- + 🦀 Testing synchronous exception handling by causing a page fault + ------------------------------------------------------------------- + + [ 0.002782] Writing to bottom of address space to address 1 GiB... + [ 0.004623] Kernel panic! + + Panic location: + File 'kernel/src/_arch/aarch64/exception.rs', line 59, column 5 + + CPU Exception! + + ESR_EL1: 0x96000004 + Exception Class (EC) : 0x25 - Data Abort, current EL + Instr Specific Syndrome (ISS): 0x4 + FAR_EL1: 0x0000000040000000 + + [...] + + Backtrace: + ---------------------------------------------------------------------------------------------- + Address Function containing address + ---------------------------------------------------------------------------------------------- + 1. ffffffffc0005560 | libkernel::panic_wait::_panic_print + 2. ffffffffc00054a0 | rust_begin_unwind + 3. ffffffffc0002950 | core::panicking::panic_fmt + 4. ffffffffc0004898 | current_elx_synchronous + 5. ffffffffc0000a74 | __vector_current_elx_synchronous + 6. ffffffffc000111c | kernel_init + ---------------------------------------------------------------------------------------------- + + ------------------------------------------------------------------- + ✅ Success: 02_exception_sync_page_fault.rs + ------------------------------------------------------------------- +``` + +## Diff to previous +```diff + +diff -uNr 17_kernel_symbols/Cargo.toml 18_backtrace/Cargo.toml +--- 17_kernel_symbols/Cargo.toml ++++ 18_backtrace/Cargo.toml +@@ -8,3 +8,4 @@ + + [profile.release] + lto = true ++debug = true + +diff -uNr 17_kernel_symbols/kernel/Cargo.toml 18_backtrace/kernel/Cargo.toml +--- 17_kernel_symbols/kernel/Cargo.toml ++++ 18_backtrace/kernel/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.17.0" ++version = "0.18.0" + authors = ["Andre Richter "] + edition = "2021" + +@@ -56,3 +56,15 @@ + [[test]] + name = "03_exception_restore_sanity" + harness = false ++ ++[[test]] ++name = "05_backtrace_sanity" ++harness = false ++ ++[[test]] ++name = "06_backtrace_invalid_frame" ++harness = false ++ ++[[test]] ++name = "07_backtrace_invalid_link" ++harness = false + +diff -uNr 17_kernel_symbols/kernel/src/_arch/aarch64/backtrace.rs 18_backtrace/kernel/src/_arch/aarch64/backtrace.rs +--- 17_kernel_symbols/kernel/src/_arch/aarch64/backtrace.rs ++++ 18_backtrace/kernel/src/_arch/aarch64/backtrace.rs +@@ -0,0 +1,136 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Architectural backtracing support. ++//! ++//! # Orientation ++//! ++//! Since arch modules are imported into generic modules using the path attribute, the path of this ++//! file is: ++//! ++//! crate::backtrace::arch_backtrace ++ ++use crate::{ ++ backtrace::BacktraceItem, ++ memory::{Address, Virtual}, ++}; ++use aarch64_cpu::registers::*; ++use tock_registers::interfaces::Readable; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// A Stack frame record. ++/// ++/// # Note ++/// ++/// The convention is that `previous_record` is valid as long as it contains a non-null value. ++/// Therefore, it is possible to type the member as `Option<&StackFrameRecord>` because of Rust's ++/// `null-pointer optimization`. ++#[repr(C)] ++struct StackFrameRecord<'a> { ++ previous_record: Option<&'a StackFrameRecord<'a>>, ++ link: Address, ++} ++ ++struct StackFrameRecordIterator<'a> { ++ cur: &'a StackFrameRecord<'a>, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl<'a> Iterator for StackFrameRecordIterator<'a> { ++ type Item = BacktraceItem; ++ ++ fn next(&mut self) -> Option { ++ static ABORT_FRAME: StackFrameRecord = StackFrameRecord { ++ previous_record: None, ++ link: Address::new(0), ++ }; ++ ++ // If previous is None, this is the root frame, so iteration will stop here. ++ let previous = self.cur.previous_record?; ++ ++ // Need to abort if the pointer to the previous frame record is invalid. ++ let prev_addr = Address::::new(previous as *const _ as usize); ++ if !prev_addr.is_valid_stack_addr() { ++ // This allows to return the error and then stop on the next iteration. ++ self.cur = &ABORT_FRAME; ++ return Some(BacktraceItem::InvalidFramePointer(prev_addr)); ++ } ++ ++ let ret = if !self.cur.link.is_valid_code_addr() { ++ Some(BacktraceItem::InvalidLink(self.cur.link)) ++ } else { ++ // The link points to the instruction to be executed _after_ returning from a branch. ++ // However, we want to show the instruction that caused the branch, so subtract by one ++ // instruction. ++ // ++ // This might be called from panic!, so it must not panic itself on the subtraction. ++ let link = if self.cur.link >= Address::new(4) { ++ self.cur.link - 4 ++ } else { ++ self.cur.link ++ }; ++ ++ Some(BacktraceItem::Link(link)) ++ }; ++ ++ // Advance the iterator. ++ self.cur = previous; ++ ++ ret ++ } ++} ++ ++fn stack_frame_record_iterator<'a>() -> Option> { ++ let fp = Address::::new(FP.get() as usize); ++ if !fp.is_valid_stack_addr() { ++ return None; ++ } ++ ++ Some(StackFrameRecordIterator { ++ cur: unsafe { &*(fp.as_usize() as *const _) }, ++ }) ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++/// Architectural implementation of the backtrace. ++pub fn backtrace(f: impl FnOnce(Option<&mut dyn Iterator>)) { ++ f(stack_frame_record_iterator().as_mut().map(|s| s as _)) ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Testing ++//-------------------------------------------------------------------------------------------------- ++ ++#[cfg(feature = "test_build")] ++#[inline(always)] ++/// Hack for corrupting the previous frame address in the current stack frame. ++/// ++/// # Safety ++/// ++/// - To be used only by testing code. ++pub unsafe fn corrupt_previous_frame_addr() { ++ let sf = FP.get() as *mut usize; ++ *sf = 0x123; ++} ++ ++#[cfg(feature = "test_build")] ++#[inline(always)] ++/// Hack for corrupting the link in the current stack frame. ++/// ++/// # Safety ++/// ++/// - To be used only by testing code. ++pub unsafe fn corrupt_link() { ++ let sf = FP.get() as *mut StackFrameRecord; ++ (*sf).link = Address::new(0x456); ++} + +diff -uNr 17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.rs 18_backtrace/kernel/src/_arch/aarch64/cpu/boot.rs +--- 17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.rs ++++ 18_backtrace/kernel/src/_arch/aarch64/cpu/boot.rs +@@ -13,7 +13,10 @@ + + use crate::{memory, memory::Address}; + use aarch64_cpu::{asm, registers::*}; +-use core::arch::global_asm; ++use core::{ ++ arch::global_asm, ++ sync::atomic::{compiler_fence, Ordering}, ++}; + use tock_registers::interfaces::Writeable; + + // Assembly counterpart to this file. +@@ -67,6 +70,18 @@ + SP_EL1.set(virt_boot_core_stack_end_exclusive_addr); + } + ++/// Reset the backtrace by setting link register and frame pointer to zero. ++/// ++/// # Safety ++/// ++/// - This function must only be used immediately before entering EL1. ++#[inline(always)] ++unsafe fn prepare_backtrace_reset() { ++ compiler_fence(Ordering::SeqCst); ++ FP.set(0); ++ LR.set(0); ++} ++ + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -93,6 +108,9 @@ + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + ++ // Make the function we return to the root of a backtrace. ++ prepare_backtrace_reset(); ++ + // Use `eret` to "return" to EL1. Since virtual memory will already be enabled, this results in + // execution of kernel_init() in EL1 from its _virtual address_. + asm::eret() + +diff -uNr 17_kernel_symbols/kernel/src/_arch/aarch64/exception.rs 18_backtrace/kernel/src/_arch/aarch64/exception.rs +--- 17_kernel_symbols/kernel/src/_arch/aarch64/exception.rs ++++ 18_backtrace/kernel/src/_arch/aarch64/exception.rs +@@ -20,7 +20,11 @@ + }; + + // Assembly counterpart to this file. +-global_asm!(include_str!("exception.s")); ++global_asm!( ++ include_str!("exception.s"), ++ CONST_ESR_EL1_EC_SHIFT = const 26, ++ CONST_ESR_EL1_EC_VALUE_SVC64 = const 0x15 ++); + + //-------------------------------------------------------------------------------------------------- + // Private Definitions + +diff -uNr 17_kernel_symbols/kernel/src/_arch/aarch64/exception.s 18_backtrace/kernel/src/_arch/aarch64/exception.s +--- 17_kernel_symbols/kernel/src/_arch/aarch64/exception.s ++++ 18_backtrace/kernel/src/_arch/aarch64/exception.s +@@ -8,10 +8,10 @@ + + /// Call the function provided by parameter `\handler` after saving the exception context. Provide + /// the context as the first parameter to '\handler'. +-.macro CALL_WITH_CONTEXT handler ++.macro CALL_WITH_CONTEXT handler is_lower_el is_sync + __vector_\handler: + // Make room on the stack for the exception context. +- sub sp, sp, #16 * 17 ++ sub sp, sp, #16 * 18 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] +@@ -39,6 +39,42 @@ + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + ++ // Build a stack frame for backtracing. ++.if \is_lower_el == 1 ++ // If we came from a lower EL, make it a root frame (by storing zero) so that the kernel ++ // does not attempt to trace into userspace. ++ stp xzr, xzr, [sp, #16 * 17] ++.else ++ // For normal branches, the link address points to the instruction to be executed _after_ ++ // returning from a branch. In a backtrace, we want to show the instruction that caused the ++ // branch, though. That is why code in backtrace.rs subtracts 4 (length of one instruction) ++ // from the link address. ++ // ++ // Here we have a special case, though, because ELR_EL1 is used instead of LR to build the ++ // stack frame, so that it becomes possible to trace beyond an exception. Hence, it must be ++ // considered that semantics for ELR_EL1 differ from case to case. ++ // ++ // Unless an "exception generating instruction" was executed, ELR_EL1 already points to the ++ // the correct instruction, and hence the subtraction by 4 in backtrace.rs would yield wrong ++ // results. To cover for this, 4 is added to ELR_EL1 below unless the cause of exception was ++ // an SVC instruction. BRK and HLT are "exception generating instructions" as well, but they ++ // are not expected and therefore left out for now. ++ // ++ // For reference: Search for "preferred exception return address" in the Architecture ++ // Reference Manual for ARMv8-A. ++.if \is_sync == 1 ++ lsr w3, w3, {CONST_ESR_EL1_EC_SHIFT} // w3 = ESR_EL1.EC ++ cmp w3, {CONST_ESR_EL1_EC_VALUE_SVC64} // w3 == SVC64 ? ++ b.eq 1f ++.endif ++ add x1, x1, #4 ++1: ++ stp x29, x1, [sp, #16 * 17] ++.endif ++ ++ // Set the frame pointer to the stack frame record. ++ add x29, sp, #16 * 17 ++ + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + +@@ -81,43 +117,43 @@ + // + // - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. + .org 0x000 +- CALL_WITH_CONTEXT current_el0_synchronous ++ CALL_WITH_CONTEXT current_el0_synchronous, 0, 1 + .org 0x080 +- CALL_WITH_CONTEXT current_el0_irq ++ CALL_WITH_CONTEXT current_el0_irq, 0, 0 + .org 0x100 + FIQ_SUSPEND + .org 0x180 +- CALL_WITH_CONTEXT current_el0_serror ++ CALL_WITH_CONTEXT current_el0_serror, 0, 0 + + // Current exception level with SP_ELx, x > 0. + .org 0x200 +- CALL_WITH_CONTEXT current_elx_synchronous ++ CALL_WITH_CONTEXT current_elx_synchronous, 0, 1 + .org 0x280 +- CALL_WITH_CONTEXT current_elx_irq ++ CALL_WITH_CONTEXT current_elx_irq, 0, 0 + .org 0x300 + FIQ_SUSPEND + .org 0x380 +- CALL_WITH_CONTEXT current_elx_serror ++ CALL_WITH_CONTEXT current_elx_serror, 0, 0 + + // Lower exception level, AArch64 + .org 0x400 +- CALL_WITH_CONTEXT lower_aarch64_synchronous ++ CALL_WITH_CONTEXT lower_aarch64_synchronous, 1, 1 + .org 0x480 +- CALL_WITH_CONTEXT lower_aarch64_irq ++ CALL_WITH_CONTEXT lower_aarch64_irq, 1, 0 + .org 0x500 + FIQ_SUSPEND + .org 0x580 +- CALL_WITH_CONTEXT lower_aarch64_serror ++ CALL_WITH_CONTEXT lower_aarch64_serror, 1, 0 + + // Lower exception level, AArch32 + .org 0x600 +- CALL_WITH_CONTEXT lower_aarch32_synchronous ++ CALL_WITH_CONTEXT lower_aarch32_synchronous, 1, 0 + .org 0x680 +- CALL_WITH_CONTEXT lower_aarch32_irq ++ CALL_WITH_CONTEXT lower_aarch32_irq, 1, 0 + .org 0x700 + FIQ_SUSPEND + .org 0x780 +- CALL_WITH_CONTEXT lower_aarch32_serror ++ CALL_WITH_CONTEXT lower_aarch32_serror, 1, 0 + .org 0x800 + + //------------------------------------------------------------------------------ +@@ -146,7 +182,7 @@ + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + +- add sp, sp, #16 * 17 ++ add sp, sp, #16 * 18 + + eret + + +diff -uNr 17_kernel_symbols/kernel/src/backtrace.rs 18_backtrace/kernel/src/backtrace.rs +--- 17_kernel_symbols/kernel/src/backtrace.rs ++++ 18_backtrace/kernel/src/backtrace.rs +@@ -0,0 +1,114 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Backtracing support. ++ ++#[cfg(target_arch = "aarch64")] ++#[path = "_arch/aarch64/backtrace.rs"] ++mod arch_backtrace; ++ ++use crate::{ ++ memory::{Address, Virtual}, ++ symbols, ++}; ++use core::fmt; ++ ++//-------------------------------------------------------------------------------------------------- ++// Architectural Public Reexports ++//-------------------------------------------------------------------------------------------------- ++#[cfg(feature = "test_build")] ++pub use arch_backtrace::{corrupt_link, corrupt_previous_frame_addr}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// A backtrace item. ++#[allow(missing_docs)] ++pub enum BacktraceItem { ++ InvalidFramePointer(Address), ++ InvalidLink(Address), ++ Link(Address), ++} ++ ++/// Pseudo-struct for printing a backtrace using its fmt::Display implementation. ++pub struct Backtrace; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl fmt::Display for Backtrace { ++ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ++ writeln!(f, "Backtrace:")?; ++ writeln!( ++ f, ++ " ----------------------------------------------------------------------------------------------" ++ )?; ++ writeln!( ++ f, ++ " Address Function containing address" ++ )?; ++ writeln!( ++ f, ++ " ----------------------------------------------------------------------------------------------" ++ )?; ++ ++ let mut fmt_res: fmt::Result = Ok(()); ++ let trace_formatter = ++ |maybe_iter: Option<&mut dyn Iterator>| match maybe_iter { ++ None => fmt_res = writeln!(f, "ERROR! No valid stack frame found"), ++ Some(iter) => { ++ // Since the backtrace is printed, the first function is always ++ // core::fmt::write. Skip 1 so it is excluded and doesn't bloat the output. ++ for (i, backtrace_res) in iter.skip(1).enumerate() { ++ match backtrace_res { ++ BacktraceItem::InvalidFramePointer(addr) => { ++ fmt_res = writeln!( ++ f, ++ " {:>2}. ERROR! \ ++ Encountered invalid frame pointer ({}) during backtrace", ++ i + 1, ++ addr ++ ); ++ } ++ BacktraceItem::InvalidLink(addr) => { ++ fmt_res = writeln!( ++ f, ++ " {:>2}. ERROR! \ ++ Link address ({}) is not contained in kernel .text section", ++ i + 1, ++ addr ++ ); ++ } ++ BacktraceItem::Link(addr) => { ++ fmt_res = writeln!( ++ f, ++ " {:>2}. {:016x} | {:<50}", ++ i + 1, ++ addr.as_usize(), ++ match symbols::lookup_symbol(addr) { ++ Some(sym) => sym.name(), ++ _ => "Symbol not found", ++ } ++ ) ++ } ++ }; ++ ++ if fmt_res.is_err() { ++ break; ++ } ++ } ++ } ++ }; ++ ++ arch_backtrace::backtrace(trace_formatter); ++ fmt_res?; ++ ++ writeln!( ++ f, ++ " ----------------------------------------------------------------------------------------------" ++ ) ++ } ++} + +diff -uNr 17_kernel_symbols/kernel/src/bsp/raspberrypi/memory/mmu.rs 18_backtrace/kernel/src/bsp/raspberrypi/memory/mmu.rs +--- 17_kernel_symbols/kernel/src/bsp/raspberrypi/memory/mmu.rs ++++ 18_backtrace/kernel/src/bsp/raspberrypi/memory/mmu.rs +@@ -80,16 +80,6 @@ + size >> KernelGranule::SHIFT + } + +-/// The code pages of the kernel binary. +-fn virt_code_region() -> MemoryRegion { +- let num_pages = size_to_num_pages(super::code_size()); +- +- let start_page_addr = super::virt_code_start(); +- let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); +- +- MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +-} +- + /// The data pages of the kernel binary. + fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); +@@ -100,16 +90,6 @@ + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) + } + +-/// The boot core stack pages. +-fn virt_boot_core_stack_region() -> MemoryRegion { +- let num_pages = size_to_num_pages(super::boot_core_stack_size()); +- +- let start_page_addr = super::virt_boot_core_stack_start(); +- let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); +- +- MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +-} +- + // There is no reason to expect the following conversions to fail, since they were generated offline + // by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. + fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { +@@ -132,6 +112,26 @@ + // Public Code + //-------------------------------------------------------------------------------------------------- + ++/// The code pages of the kernel binary. ++pub fn virt_code_region() -> MemoryRegion { ++ let num_pages = size_to_num_pages(super::code_size()); ++ ++ let start_page_addr = super::virt_code_start(); ++ let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); ++ ++ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) ++} ++ ++/// The boot core stack pages. ++pub fn virt_boot_core_stack_region() -> MemoryRegion { ++ let num_pages = size_to_num_pages(super::boot_core_stack_size()); ++ ++ let start_page_addr = super::virt_boot_core_stack_start(); ++ let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); ++ ++ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) ++} ++ + /// Return a reference to the kernel's translation tables. + pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES + +diff -uNr 17_kernel_symbols/kernel/src/lib.rs 18_backtrace/kernel/src/lib.rs +--- 17_kernel_symbols/kernel/src/lib.rs ++++ 18_backtrace/kernel/src/lib.rs +@@ -133,6 +133,7 @@ + mod panic_wait; + mod synchronization; + ++pub mod backtrace; + pub mod bsp; + pub mod common; + pub mod console; + +diff -uNr 17_kernel_symbols/kernel/src/memory.rs 18_backtrace/kernel/src/memory.rs +--- 17_kernel_symbols/kernel/src/memory.rs ++++ 18_backtrace/kernel/src/memory.rs +@@ -95,6 +95,18 @@ + } + } + ++impl Sub for Address { ++ type Output = Self; ++ ++ #[inline(always)] ++ fn sub(self, rhs: usize) -> Self::Output { ++ match self.value.checked_sub(rhs) { ++ None => panic!("Overflow on Address::sub"), ++ Some(x) => Self::new(x), ++ } ++ } ++} ++ + impl Sub> for Address { + type Output = Self; + +@@ -107,6 +119,18 @@ + } + } + ++impl Address { ++ /// Checks if the address is part of the boot core stack region. ++ pub fn is_valid_stack_addr(&self) -> bool { ++ bsp::memory::mmu::virt_boot_core_stack_region().contains(*self) ++ } ++ ++ /// Checks if the address is part of the kernel code region. ++ pub fn is_valid_code_addr(&self) -> bool { ++ bsp::memory::mmu::virt_code_region().contains(*self) ++ } ++} ++ + impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + +diff -uNr 17_kernel_symbols/kernel/src/panic_wait.rs 18_backtrace/kernel/src/panic_wait.rs +--- 17_kernel_symbols/kernel/src/panic_wait.rs ++++ 18_backtrace/kernel/src/panic_wait.rs +@@ -4,7 +4,7 @@ + + //! A panic handler that infinitely waits. + +-use crate::{cpu, exception, println}; ++use crate::{backtrace, cpu, exception, println}; + use core::panic::PanicInfo; + + //-------------------------------------------------------------------------------------------------- +@@ -73,6 +73,7 @@ + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ ++ {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), +@@ -80,6 +81,7 @@ + line, + column, + info.message().unwrap_or(&format_args!("")), ++ backtrace::Backtrace + ); + + _panic_exit() + +diff -uNr 17_kernel_symbols/kernel/src/state.rs 18_backtrace/kernel/src/state.rs +--- 17_kernel_symbols/kernel/src/state.rs ++++ 18_backtrace/kernel/src/state.rs +@@ -52,7 +52,7 @@ + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + +- /// Create a new instance. ++ /// Create an instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + +diff -uNr 17_kernel_symbols/kernel/tests/05_backtrace_sanity.rb 18_backtrace/kernel/tests/05_backtrace_sanity.rb +--- 17_kernel_symbols/kernel/tests/05_backtrace_sanity.rb ++++ 18_backtrace/kernel/tests/05_backtrace_sanity.rb +@@ -0,0 +1,39 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2022-2023 Andre Richter ++ ++require 'console_io_test' ++ ++# Verify that panic produces a backtrace. ++class PanicBacktraceTest < SubtestBase ++ def name ++ 'Panic produces backtrace' ++ end ++ ++ def run(qemu_out, _qemu_in) ++ expect_or_raise(qemu_out, 'Kernel panic!') ++ expect_or_raise(qemu_out, 'Backtrace:') ++ end ++end ++ ++# Verify backtrace correctness. ++class BacktraceCorrectnessTest < SubtestBase ++ def name ++ 'Backtrace is correct' ++ end ++ ++ def run(qemu_out, _qemu_in) ++ expect_or_raise(qemu_out, '| core::panicking::panic') ++ expect_or_raise(qemu_out, '| _05_backtrace_sanity::nested') ++ expect_or_raise(qemu_out, '| kernel_init') ++ end ++end ++ ++##-------------------------------------------------------------------------------------------------- ++## Test registration ++##-------------------------------------------------------------------------------------------------- ++def subtest_collection ++ [PanicBacktraceTest.new, BacktraceCorrectnessTest.new] ++end + +diff -uNr 17_kernel_symbols/kernel/tests/05_backtrace_sanity.rs 18_backtrace/kernel/tests/05_backtrace_sanity.rs +--- 17_kernel_symbols/kernel/tests/05_backtrace_sanity.rs ++++ 18_backtrace/kernel/tests/05_backtrace_sanity.rs +@@ -0,0 +1,31 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Test if backtracing code detects an invalid frame pointer. ++ ++#![feature(format_args_nl)] ++#![no_main] ++#![no_std] ++ ++/// Console tests should time out on the I/O harness in case of panic. ++mod panic_wait_forever; ++ ++use libkernel::{bsp, cpu, exception, memory}; ++ ++#[inline(never)] ++fn nested() { ++ panic!() ++} ++ ++#[no_mangle] ++unsafe fn kernel_init() -> ! { ++ exception::handling_init(); ++ memory::init(); ++ bsp::driver::qemu_bring_up_console(); ++ ++ nested(); ++ ++ // The QEMU process running this test will be closed by the I/O test harness. ++ cpu::wait_forever() ++} + +diff -uNr 17_kernel_symbols/kernel/tests/06_backtrace_invalid_frame.rb 18_backtrace/kernel/tests/06_backtrace_invalid_frame.rb +--- 17_kernel_symbols/kernel/tests/06_backtrace_invalid_frame.rb ++++ 18_backtrace/kernel/tests/06_backtrace_invalid_frame.rb +@@ -0,0 +1,26 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2022-2023 Andre Richter ++ ++require 'console_io_test' ++ ++# Test detection of invalid frame pointers. ++class InvalidFramePointerTest < SubtestBase ++ def name ++ 'Detect invalid frame pointer' ++ end ++ ++ def run(qemu_out, _qemu_in) ++ expect_or_raise(qemu_out, ++ /Encountered invalid frame pointer \(.*\) during backtrace/) ++ end ++end ++ ++##-------------------------------------------------------------------------------------------------- ++## Test registration ++##-------------------------------------------------------------------------------------------------- ++def subtest_collection ++ [InvalidFramePointerTest.new] ++end + +diff -uNr 17_kernel_symbols/kernel/tests/06_backtrace_invalid_frame.rs 18_backtrace/kernel/tests/06_backtrace_invalid_frame.rs +--- 17_kernel_symbols/kernel/tests/06_backtrace_invalid_frame.rs ++++ 18_backtrace/kernel/tests/06_backtrace_invalid_frame.rs +@@ -0,0 +1,33 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Test if backtracing code detects an invalid frame pointer. ++ ++#![feature(format_args_nl)] ++#![no_main] ++#![no_std] ++ ++/// Console tests should time out on the I/O harness in case of panic. ++mod panic_wait_forever; ++ ++use libkernel::{backtrace, bsp, cpu, exception, memory}; ++ ++#[inline(never)] ++fn nested() { ++ unsafe { backtrace::corrupt_previous_frame_addr() }; ++ ++ panic!() ++} ++ ++#[no_mangle] ++unsafe fn kernel_init() -> ! { ++ exception::handling_init(); ++ memory::init(); ++ bsp::driver::qemu_bring_up_console(); ++ ++ nested(); ++ ++ // The QEMU process running this test will be closed by the I/O test harness. ++ cpu::wait_forever() ++} + +diff -uNr 17_kernel_symbols/kernel/tests/07_backtrace_invalid_link.rb 18_backtrace/kernel/tests/07_backtrace_invalid_link.rb +--- 17_kernel_symbols/kernel/tests/07_backtrace_invalid_link.rb ++++ 18_backtrace/kernel/tests/07_backtrace_invalid_link.rb +@@ -0,0 +1,25 @@ ++# frozen_string_literal: true ++ ++# SPDX-License-Identifier: MIT OR Apache-2.0 ++# ++# Copyright (c) 2022-2023 Andre Richter ++ ++require 'console_io_test' ++ ++# Test detection of invalid link. ++class InvalidLinkTest < SubtestBase ++ def name ++ 'Detect invalid link' ++ end ++ ++ def run(qemu_out, _qemu_in) ++ expect_or_raise(qemu_out, /Link address \(.*\) is not contained in kernel .text section/) ++ end ++end ++ ++##-------------------------------------------------------------------------------------------------- ++## Test registration ++##-------------------------------------------------------------------------------------------------- ++def subtest_collection ++ [InvalidLinkTest.new] ++end + +diff -uNr 17_kernel_symbols/kernel/tests/07_backtrace_invalid_link.rs 18_backtrace/kernel/tests/07_backtrace_invalid_link.rs +--- 17_kernel_symbols/kernel/tests/07_backtrace_invalid_link.rs ++++ 18_backtrace/kernel/tests/07_backtrace_invalid_link.rs +@@ -0,0 +1,38 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Test if backtracing code detects an invalid link. ++ ++#![feature(format_args_nl)] ++#![no_main] ++#![no_std] ++ ++/// Console tests should time out on the I/O harness in case of panic. ++mod panic_wait_forever; ++ ++use libkernel::{backtrace, bsp, cpu, exception, memory}; ++ ++#[inline(never)] ++fn nested_2() -> &'static str { ++ unsafe { backtrace::corrupt_link() }; ++ libkernel::println!("{}", libkernel::backtrace::Backtrace); ++ "foo" ++} ++ ++#[inline(never)] ++fn nested_1() { ++ libkernel::println!("{}", nested_2()) ++} ++ ++#[no_mangle] ++unsafe fn kernel_init() -> ! { ++ exception::handling_init(); ++ memory::init(); ++ bsp::driver::qemu_bring_up_console(); ++ ++ nested_1(); ++ ++ // The QEMU process running this test will be closed by the I/O test harness. ++ cpu::wait_forever() ++} + +diff -uNr 17_kernel_symbols/Makefile 18_backtrace/Makefile +--- 17_kernel_symbols/Makefile ++++ 18_backtrace/Makefile +@@ -43,7 +43,7 @@ + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi +- RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 ++ RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -C force-frame-pointers + else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img +@@ -57,7 +57,7 @@ + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi +- RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 ++ RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -C force-frame-pointers + endif + + # Export for build.rs. +@@ -122,10 +122,12 @@ + $(FEATURES) \ + --release + +-RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) ++# build-std can be skipped for helper commands that do not rely on correct stack frames and other ++# custom compiler options. This results in a huge speedup. ++RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -Z build-std=core --manifest-path $(KERNEL_MANIFEST) + DOC_CMD = cargo doc $(COMPILER_ARGS) + CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +-TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) ++TEST_CMD = cargo test $(COMPILER_ARGS) -Z build-std=core --manifest-path $(KERNEL_MANIFEST) + OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary +@@ -302,8 +304,7 @@ + ##------------------------------------------------------------------------------ + ## Start GDB session + ##------------------------------------------------------------------------------ +-gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +-gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 ++gdb-opt0: RUSTC_MISC_ARGS += -C opt-level=0 + gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + +diff -uNr 17_kernel_symbols/tools/translation_table_tool/bsp.rb 18_backtrace/tools/translation_table_tool/bsp.rb +--- 17_kernel_symbols/tools/translation_table_tool/bsp.rb ++++ 18_backtrace/tools/translation_table_tool/bsp.rb +@@ -45,6 +45,10 @@ + raise + end + +- x.scan(/\d+/).join.to_i(16) ++ # Extract the hex literal with underscores like 0x0123_abcd. ++ x = x.scan(/0x[\h_]*/)[0] ++ ++ # Further remove x and _ and convert to int. ++ x.scan(/\h+/).join.to_i(16) + end + end + +diff -uNr 17_kernel_symbols/tools/translation_table_tool/generic.rb 18_backtrace/tools/translation_table_tool/generic.rb +--- 17_kernel_symbols/tools/translation_table_tool/generic.rb ++++ 18_backtrace/tools/translation_table_tool/generic.rb +@@ -109,13 +109,23 @@ + @attributes = attributes + end + ++ def size_human_readable(size) ++ if size >= (1024 * 1024) ++ "#{(size / (1024 * 1024)).to_s.rjust(3)} MiB" ++ elsif size >= 1024 ++ "#{(size / 1024).to_s.rjust(3)} KiB" ++ else ++ raise ++ end ++ end ++ + def to_s + name = @name.ljust(self.class.max_section_name_length) + virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) + phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) +- size = ((@virt_region.size * 65_536) / 1024).to_s.rjust(3) ++ size = size_human_readable(@virt_region.size * 65_536) + +- "#{name} | #{virt_start} | #{phys_start} | #{size} KiB | #{@attributes}" ++ "#{name} | #{virt_start} | #{phys_start} | #{size} | #{@attributes}" + end + + def self.print_divider + +``` diff --git a/18_backtrace/kernel/Cargo.toml b/18_backtrace/kernel/Cargo.toml new file mode 100644 index 000000000..bba97b8dd --- /dev/null +++ b/18_backtrace/kernel/Cargo.toml @@ -0,0 +1,70 @@ +[package] +name = "mingo" +version = "0.18.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } +debug-symbol-types = { path = "../libraries/debug-symbol-types" } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##-------------------------------------------------------------------------------------------------- +## Testing +##-------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false + +[[test]] +name = "05_backtrace_sanity" +harness = false + +[[test]] +name = "06_backtrace_invalid_frame" +harness = false + +[[test]] +name = "07_backtrace_invalid_link" +harness = false diff --git a/18_backtrace/kernel/build.rs b/18_backtrace/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/18_backtrace/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/backtrace.rs b/18_backtrace/kernel/src/_arch/aarch64/backtrace.rs new file mode 100644 index 000000000..c2fb8dcb4 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/backtrace.rs @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Architectural backtracing support. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::backtrace::arch_backtrace + +use crate::{ + backtrace::BacktraceItem, + memory::{Address, Virtual}, +}; +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// A Stack frame record. +/// +/// # Note +/// +/// The convention is that `previous_record` is valid as long as it contains a non-null value. +/// Therefore, it is possible to type the member as `Option<&StackFrameRecord>` because of Rust's +/// `null-pointer optimization`. +#[repr(C)] +struct StackFrameRecord<'a> { + previous_record: Option<&'a StackFrameRecord<'a>>, + link: Address, +} + +struct StackFrameRecordIterator<'a> { + cur: &'a StackFrameRecord<'a>, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl<'a> Iterator for StackFrameRecordIterator<'a> { + type Item = BacktraceItem; + + fn next(&mut self) -> Option { + static ABORT_FRAME: StackFrameRecord = StackFrameRecord { + previous_record: None, + link: Address::new(0), + }; + + // If previous is None, this is the root frame, so iteration will stop here. + let previous = self.cur.previous_record?; + + // Need to abort if the pointer to the previous frame record is invalid. + let prev_addr = Address::::new(previous as *const _ as usize); + if !prev_addr.is_valid_stack_addr() { + // This allows to return the error and then stop on the next iteration. + self.cur = &ABORT_FRAME; + return Some(BacktraceItem::InvalidFramePointer(prev_addr)); + } + + let ret = if !self.cur.link.is_valid_code_addr() { + Some(BacktraceItem::InvalidLink(self.cur.link)) + } else { + // The link points to the instruction to be executed _after_ returning from a branch. + // However, we want to show the instruction that caused the branch, so subtract by one + // instruction. + // + // This might be called from panic!, so it must not panic itself on the subtraction. + let link = if self.cur.link >= Address::new(4) { + self.cur.link - 4 + } else { + self.cur.link + }; + + Some(BacktraceItem::Link(link)) + }; + + // Advance the iterator. + self.cur = previous; + + ret + } +} + +fn stack_frame_record_iterator<'a>() -> Option> { + let fp = Address::::new(FP.get() as usize); + if !fp.is_valid_stack_addr() { + return None; + } + + Some(StackFrameRecordIterator { + cur: unsafe { &*(fp.as_usize() as *const _) }, + }) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Architectural implementation of the backtrace. +pub fn backtrace(f: impl FnOnce(Option<&mut dyn Iterator>)) { + f(stack_frame_record_iterator().as_mut().map(|s| s as _)) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(feature = "test_build")] +#[inline(always)] +/// Hack for corrupting the previous frame address in the current stack frame. +/// +/// # Safety +/// +/// - To be used only by testing code. +pub unsafe fn corrupt_previous_frame_addr() { + let sf = FP.get() as *mut usize; + *sf = 0x123; +} + +#[cfg(feature = "test_build")] +#[inline(always)] +/// Hack for corrupting the link in the current stack frame. +/// +/// # Safety +/// +/// - To be used only by testing code. +pub unsafe fn corrupt_link() { + let sf = FP.get() as *mut StackFrameRecord; + (*sf).link = Address::new(0x456); +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/cpu.rs b/18_backtrace/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/cpu/boot.rs b/18_backtrace/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..b8033fbe8 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use crate::{memory, memory::Address}; +use aarch64_cpu::{asm, registers::*}; +use core::{ + arch::global_asm, + sync::atomic::{compiler_fence, Ordering}, +}; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(virt_kernel_init_addr); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(virt_boot_core_stack_end_exclusive_addr); +} + +/// Reset the backtrace by setting link register and frame pointer to zero. +/// +/// # Safety +/// +/// - This function must only be used immediately before entering EL1. +#[inline(always)] +unsafe fn prepare_backtrace_reset() { + compiler_fence(Ordering::SeqCst); + FP.set(0); + LR.set(0); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) -> ! { + prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr, + virt_kernel_init_addr, + ); + + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + + // Make the function we return to the root of a backtrace. + prepare_backtrace_reset(); + + // Use `eret` to "return" to EL1. Since virtual memory will already be enabled, this results in + // execution of kernel_init() in EL1 from its _virtual address_. + asm::eret() +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/cpu/boot.s b/18_backtrace/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..65d71b1a7 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +// Load the address of a symbol into a register, absolute. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_ABS register, symbol + movz \register, #:abs_g3:\symbol + movk \register, #:abs_g2_nc:\symbol + movk \register, #:abs_g1_nc:\symbol + movk \register, #:abs_g0_nc:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Load the base address of the kernel's translation tables. + ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + + // Load the _absolute_ addresses of the following symbols. Since the kernel is linked at + // the top of the 64 bit address space, these are effectively virtual addresses. + ADR_ABS x1, __boot_core_stack_end_exclusive + ADR_ABS x2, kernel_init + + // Load the PC-relative address of the stack and set the stack pointer. + // + // Since _start() is the first function that runs after the firmware has loaded the kernel + // into memory, retrieving this symbol PC-relative returns the "physical" address. + // + // Setting the stack pointer to this value ensures that anything that still runs in EL2, + // until the kernel returns to EL1 with the MMU enabled, works as well. After the return to + // EL1, the virtual address of the stack retrieved above will be used. + ADR_REL x3, __boot_core_stack_end_exclusive + mov sp, x3 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x4, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x5, CNTFRQ_EL0 + cmp x5, xzr + b.eq .L_parking_loop + str w5, [x4] + + // Jump to Rust code. x0, x1 and x2 hold the function arguments provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/18_backtrace/kernel/src/_arch/aarch64/cpu/smp.rs b/18_backtrace/kernel/src/_arch/aarch64/cpu/smp.rs new file mode 100644 index 000000000..491920389 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/exception.rs b/18_backtrace/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..ab4640815 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,325 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use crate::{exception, memory, symbols}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!( + include_str!("exception.s"), + CONST_ESR_EL1_EC_SHIFT = const 26, + CONST_ESR_EL1_EC_VALUE_SVC64 = const 0x15 +); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!( + f, + " Symbol: {}", + match symbols::lookup_symbol(memory::Address::new(self.elr_el1 as usize)) { + Some(sym) => sym.name(), + _ => "Symbol not found", + } + )?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/exception.s b/18_backtrace/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..cdef8c586 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler is_lower_el is_sync +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 18 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // Build a stack frame for backtracing. +.if \is_lower_el == 1 + // If we came from a lower EL, make it a root frame (by storing zero) so that the kernel + // does not attempt to trace into userspace. + stp xzr, xzr, [sp, #16 * 17] +.else + // For normal branches, the link address points to the instruction to be executed _after_ + // returning from a branch. In a backtrace, we want to show the instruction that caused the + // branch, though. That is why code in backtrace.rs subtracts 4 (length of one instruction) + // from the link address. + // + // Here we have a special case, though, because ELR_EL1 is used instead of LR to build the + // stack frame, so that it becomes possible to trace beyond an exception. Hence, it must be + // considered that semantics for ELR_EL1 differ from case to case. + // + // Unless an "exception generating instruction" was executed, ELR_EL1 already points to the + // the correct instruction, and hence the subtraction by 4 in backtrace.rs would yield wrong + // results. To cover for this, 4 is added to ELR_EL1 below unless the cause of exception was + // an SVC instruction. BRK and HLT are "exception generating instructions" as well, but they + // are not expected and therefore left out for now. + // + // For reference: Search for "preferred exception return address" in the Architecture + // Reference Manual for ARMv8-A. +.if \is_sync == 1 + lsr w3, w3, {CONST_ESR_EL1_EC_SHIFT} // w3 = ESR_EL1.EC + cmp w3, {CONST_ESR_EL1_EC_VALUE_SVC64} // w3 == SVC64 ? + b.eq 1f +.endif + add x1, x1, #4 +1: + stp x29, x1, [sp, #16 * 17] +.endif + + // Set the frame pointer to the stack frame record. + add x29, sp, #16 * 17 + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous, 0, 1 +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq, 0, 0 +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror, 0, 0 + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous, 0, 1 +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq, 0, 0 +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror, 0, 0 + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous, 1, 1 +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq, 1, 0 +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror, 1, 0 + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous, 1, 0 +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq, 1, 0 +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror, 1, 0 +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 18 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/18_backtrace/kernel/src/_arch/aarch64/exception/asynchronous.rs b/18_backtrace/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..811ef138e --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/memory/mmu.rs b/18_backtrace/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..984b2e04f --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::{mmu::TranslationGranule, Address, Physical}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + #[inline(always)] + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + #[inline(always)] + fn configure_translation_control(&self) { + let t1sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI1::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG1::KiB_64 + + TCR_EL1::SH1::Inner + + TCR_EL1::ORGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD1::EnableTTBR1Walks + + TCR_EL1::A1::TTBR1 + + TCR_EL1::T1SZ.val(t1sz) + + TCR_EL1::EPD0::DisableTTBR0Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Set the "Translation Table Base Register". + TTBR1_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/18_backtrace/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..21fae3b82 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,521 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, + memory::{ + self, + mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, + }, + Address, Physical, Virtual, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn virt_start_addr(&self) -> Address; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], + + /// Have the tables been initialized? + initialized: bool, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl StartAddr for [T; N] { + fn virt_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +/// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. +impl convert::TryFrom> for AttributeFields { + type Error = &'static str; + + fn try_from( + desc: InMemoryRegister, + ) -> Result { + let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { + memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, + memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, + _ => return Err("Unexpected memory attribute"), + }; + + let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, + _ => return Err("Unexpected access permission"), + }; + + let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; + + Ok(AttributeFields { + mem_attributes, + acc_perms, + execute_never, + }) + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_page_addr( + phys_output_page_addr: PageAddress, + attribute_fields: &AttributeFields, + ) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } + + /// Returns the valid bit. + fn is_valid(&self) -> bool { + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } + + /// Returns the output page. + fn output_page_addr(&self) -> PageAddress { + let shifted = InMemoryRegister::::new(self.value) + .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; + + PageAddress::from(shifted << Granule64KiB::SHIFT) + } + + /// Returns the attributes. + fn try_attributes(&self) -> Result { + InMemoryRegister::::new(self.value).try_into() + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromTop = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; + + type TableStartFromBottom = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; +} + +impl + FixedSizeTranslationTable +{ + const START_FROM_TOP_OFFSET: Address = + Address::new((usize::MAX - (Granule512MiB::SIZE * NUM_TABLES)) + 1); + + /// Create an instance. + #[allow(clippy::assertions_on_constants)] + const fn _new(for_precompute: bool) -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + initialized: for_precompute, + } + } + + pub const fn new_for_precompute() -> Self { + Self::_new(true) + } + + #[cfg(test)] + pub fn new_for_runtime() -> Self { + Self::_new(false) + } + + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { + let mut addr = virt_page_addr.into_inner(); + + if START_FROM_TOP { + addr = addr - Self::START_FROM_TOP_OFFSET; + } + + let lvl2_index = addr.as_usize() >> Granule512MiB::SHIFT; + let lvl3_index = (addr.as_usize() & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); + } + + Ok((lvl2_index, lvl3_index)) + } + + /// Returns the PageDescriptor corresponding to the supplied page address. + #[inline(always)] + fn page_descriptor_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<&PageDescriptor, &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &self.lvl3[lvl2_index][lvl3_index]; + + Ok(desc) + } + + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. + #[inline(always)] + fn set_page_descriptor_from_page_addr( + &mut self, + virt_page_addr: PageAddress, + new_desc: &PageDescriptor, + ) -> Result<(), &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &mut self.lvl3[lvl2_index][lvl3_index]; + + if desc.is_valid() { + return Err("Virtual page is already mapped"); + } + + *desc = *new_desc; + Ok(()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl + memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable +{ + fn init(&mut self) -> Result<(), &'static str> { + if self.initialized { + return Ok(()); + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { + let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); + let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; + + Ok(()) + } + + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + assert!(self.initialized, "Translation tables not initialized"); + + if virt_region.size() != phys_region.size() { + return Err("Tried to map memory regions with unequal sizes"); + } + + if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() + { + return Err("Tried to map outside of physical address space"); + } + + let iter = phys_region.into_iter().zip(virt_region.into_iter()); + for (phys_page_addr, virt_page_addr) in iter { + let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); + let virt_page = virt_page_addr; + + self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; + } + + Ok(()) + } + + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str> { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + Ok(page_desc.output_page_addr()) + } + + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + page_desc.try_attributes() + } + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str> { + let virt_page = PageAddress::from(virt_addr.align_down_page()); + let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; + + Ok(phys_page.into_inner() + virt_addr.offset_into_page()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1, true>; + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/18_backtrace/kernel/src/_arch/aarch64/time.rs b/18_backtrace/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/18_backtrace/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/18_backtrace/kernel/src/backtrace.rs b/18_backtrace/kernel/src/backtrace.rs new file mode 100644 index 000000000..a6af2fccc --- /dev/null +++ b/18_backtrace/kernel/src/backtrace.rs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Backtracing support. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/backtrace.rs"] +mod arch_backtrace; + +use crate::{ + memory::{Address, Virtual}, + symbols, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +pub use arch_backtrace::{corrupt_link, corrupt_previous_frame_addr}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A backtrace item. +#[allow(missing_docs)] +pub enum BacktraceItem { + InvalidFramePointer(Address), + InvalidLink(Address), + Link(Address), +} + +/// Pseudo-struct for printing a backtrace using its fmt::Display implementation. +pub struct Backtrace; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for Backtrace { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "Backtrace:")?; + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + )?; + writeln!( + f, + " Address Function containing address" + )?; + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + )?; + + let mut fmt_res: fmt::Result = Ok(()); + let trace_formatter = + |maybe_iter: Option<&mut dyn Iterator>| match maybe_iter { + None => fmt_res = writeln!(f, "ERROR! No valid stack frame found"), + Some(iter) => { + // Since the backtrace is printed, the first function is always + // core::fmt::write. Skip 1 so it is excluded and doesn't bloat the output. + for (i, backtrace_res) in iter.skip(1).enumerate() { + match backtrace_res { + BacktraceItem::InvalidFramePointer(addr) => { + fmt_res = writeln!( + f, + " {:>2}. ERROR! \ + Encountered invalid frame pointer ({}) during backtrace", + i + 1, + addr + ); + } + BacktraceItem::InvalidLink(addr) => { + fmt_res = writeln!( + f, + " {:>2}. ERROR! \ + Link address ({}) is not contained in kernel .text section", + i + 1, + addr + ); + } + BacktraceItem::Link(addr) => { + fmt_res = writeln!( + f, + " {:>2}. {:016x} | {:<50}", + i + 1, + addr.as_usize(), + match symbols::lookup_symbol(addr) { + Some(sym) => sym.name(), + _ => "Symbol not found", + } + ) + } + }; + + if fmt_res.is_err() { + break; + } + } + } + }; + + arch_backtrace::backtrace(trace_formatter); + fmt_res?; + + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + ) + } +} diff --git a/18_backtrace/kernel/src/bsp.rs b/18_backtrace/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/18_backtrace/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/18_backtrace/kernel/src/bsp/device_driver.rs b/18_backtrace/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..2dfaec8d6 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(feature = "bsp_rpi4")] +mod arm; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/18_backtrace/kernel/src/bsp/device_driver/arm.rs b/18_backtrace/kernel/src/bsp/device_driver/arm.rs new file mode 100644 index 000000000..8d1cbfbd8 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff --git a/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2.rs b/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2.rs new file mode 100644 index 000000000..256de7041 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new( + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, + ) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff --git a/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs b/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs new file mode 100644 index 000000000..0fd16bb38 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff --git a/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs b/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs new file mode 100644 index 000000000..1fc9d70e9 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, + state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num % 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff --git a/18_backtrace/kernel/src/bsp/device_driver/bcm.rs b/18_backtrace/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..7b7c288b7 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..812156f44 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs new file mode 100644 index 000000000..62f078002 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.periph.print_handler(); + } +} diff --git a/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs new file mode 100644 index 000000000..a26bff8d0 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), + } + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() % 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..b424d4be7 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,505 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff --git a/18_backtrace/kernel/src/bsp/device_driver/common.rs b/18_backtrace/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..3ce1d8d81 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use crate::memory::{Address, Virtual}; +use core::{fmt, marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: Address, + phantom: PhantomData T>, +} + +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: Address) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr.as_usize() as *const _) } + } +} + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/18_backtrace/kernel/src/bsp/raspberrypi.rs b/18_backtrace/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..30421dfa6 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/18_backtrace/kernel/src/bsp/raspberrypi/cpu.rs b/18_backtrace/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/18_backtrace/kernel/src/bsp/raspberrypi/driver.rs b/18_backtrace/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..a1f55b170 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, + memory, + memory::mmu::MMIODescriptor, +}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering}, +}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi3")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi4")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the UART driver. +unsafe fn post_init_uart() -> Result<(), &'static str> { + console::register_console(PL011_UART.assume_init_ref()); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_gpio() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; + + GPIO.write(device_driver::GPIO::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +unsafe fn post_init_gpio() -> Result<(), &'static str> { + GPIO.assume_init_ref().map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi3")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &periph_mmio_descriptor, + )?; + + INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi4")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); + let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; + + let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); + let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; + + INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the interrupt controller driver. +unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_gpio() -> Result<(), &'static str> { + instantiate_gpio()?; + + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( + GPIO.assume_init_ref(), + Some(post_init_gpio), + None, + ); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { + instantiate_interrupt_controller()?; + + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + INTERRUPT_CONTROLLER.assume_init_ref(), + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + use crate::cpu; + + unsafe { + instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); + console::register_console(PL011_UART.assume_init_ref()); + }; +} diff --git a/18_backtrace/kernel/src/bsp/raspberrypi/exception.rs b/18_backtrace/kernel/src/bsp/raspberrypi/exception.rs new file mode 100644 index 000000000..a9eaa6ac4 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff --git a/18_backtrace/kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/18_backtrace/kernel/src/bsp/raspberrypi/exception/asynchronous.rs new file mode 100644 index 000000000..776182fd0 --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +#[cfg(feature = "bsp_rpi3")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; + + pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +#[cfg(feature = "bsp_rpi4")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::IRQNumber; + + pub const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff --git a/18_backtrace/kernel/src/bsp/raspberrypi/kernel.ld b/18_backtrace/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..193a5200b --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,121 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +INCLUDE kernel_virt_addr_space_size.ld; + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +/* The kernel's virtual address range will be: + * + * [END_ADDRESS_INCLUSIVE, START_ADDRESS] + * [u64::MAX , (u64::MAX - __kernel_virt_addr_space_size) + 1] + */ +__kernel_virt_start_addr = ((0xffffffffffffffff - __kernel_virt_addr_space_size) + 1); + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); + segment_boot_core_stack PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __kernel_virt_start_addr; + + ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : AT(__rpi_phys_binary_load_addr) + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + .kernel_symbols : ALIGN(8) { + __kernel_symbols_start = .; + . += 32 * 1024; + } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + __data_start = .; + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + + /*********************************************************************************************** + * Guard Page + ***********************************************************************************************/ + . += PAGE_SIZE; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) + { + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/18_backtrace/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld b/18_backtrace/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld new file mode 100644 index 000000000..c5d58c30a --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld @@ -0,0 +1 @@ +__kernel_virt_addr_space_size = 1024 * 1024 * 1024 diff --git a/18_backtrace/kernel/src/bsp/raspberrypi/memory.rs b/18_backtrace/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..96a4d8c1c --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | .kernel_symbols | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | data_end_exclusive +//! | | +//! +//! +//! +//! +//! +//! The virtual memory layout is as follows: +//! +//! +---------------------------------------+ +//! | | code_start @ __kernel_virt_start_addr +//! | .text | +//! | .rodata | +//! | .got | +//! | .kernel_symbols | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_start == data_end_exclusive +//! | VA region for MMIO remapping | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_end_exclusive +//! | Unmapped guard page | +//! | | +//! +---------------------------------------+ +//! | | boot_core_stack_start +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | boot_core_stack_end_exclusive +//! | | +pub mod mmu; + +use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; + + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + + static __boot_core_stack_start: UnsafeCell<()>; + static __boot_core_stack_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + use super::*; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); + pub const PERIPHERAL_IC_SIZE: usize = 0x24; + + pub const GPIO_START: Address = Address::new(0x3F20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const END: Address = Address::new(0x4001_0000); + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const GPIO_START: Address = Address::new(0xFE20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0xFE20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const GICD_START: Address = Address::new(0xFF84_1000); + pub const GICD_SIZE: usize = 0x824; + + pub const GICC_START: Address = Address::new(0xFF84_2000); + pub const GICC_SIZE: usize = 0x14; + + pub const END: Address = Address::new(0xFF85_0000); + } + + pub const END: Address = mmio::END; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_code_start() -> PageAddress { + PageAddress::from(unsafe { __code_start.get() as usize }) +} + +/// Size of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_size() -> usize { + unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } +} + +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { + PageAddress::from(unsafe { __data_start.get() as usize }) +} + +/// Size of the data segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn data_size() -> usize { + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } +} + +/// Start page address of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_mmio_remap_start() -> PageAddress { + PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) +} + +/// Size of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn mmio_remap_size() -> usize { + unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } +} + +/// Start page address of the boot core's stack. +#[inline(always)] +fn virt_boot_core_stack_start() -> PageAddress { + PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) +} + +/// Size of the boot core's stack. +#[inline(always)] +fn boot_core_stack_size() -> usize { + unsafe { + (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Exclusive end address of the physical address space. +#[inline(always)] +pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { + PageAddress::from(map::END) +} diff --git a/18_backtrace/kernel/src/bsp/raspberrypi/memory/mmu.rs b/18_backtrace/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..c6263245a --- /dev/null +++ b/18_backtrace/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use crate::{ + memory::{ + mmu::{ + self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, + MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type KernelTranslationTable = + ::TableStartFromTop; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to +/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. +pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + +/// The kernel's virtual address space defined by this BSP. +pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// It is mandatory that InitStateLock is transparent. +/// +/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. +/// There is a unit tests that checks this porperty. +#[link_section = ".data"] +#[no_mangle] +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new_for_precompute()); + +/// This value is needed during early boot for MMU setup. +/// +/// This will be patched to the correct value by the "translation table tool" after linking. This +/// given value here is just a dummy. +#[link_section = ".text._start_arguments"] +#[no_mangle] +static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This is a hack for retrieving the value for the kernel's virtual address space size as a +/// constant from a common place, since it is needed as a compile-time/link-time constant in both, +/// the linker script and the Rust sources. +#[allow(clippy::needless_late_init)] +const fn kernel_virt_addr_space_size() -> usize { + let __kernel_virt_addr_space_size; + + include!("../kernel_virt_addr_space_size.ld"); + + __kernel_virt_addr_space_size +} + +/// Helper function for calculating the number of pages the given parameter spans. +const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); + assert!(size % KernelGranule::SIZE == 0); + + size >> KernelGranule::SHIFT +} + +/// The data pages of the kernel binary. +fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); + + let start_page_addr = super::virt_data_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +// There is no reason to expect the following conversions to fail, since they were generated offline +// by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. +fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { + let phys_start_page_addr = + generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) + .unwrap(); + + let phys_end_exclusive_page_addr = phys_start_page_addr + .checked_offset(virt_region.num_pages() as isize) + .unwrap(); + + MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) +} + +fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { + generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The code pages of the kernel binary. +pub fn virt_code_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::code_size()); + + let start_page_addr = super::virt_code_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The boot core stack pages. +pub fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); + + let start_page_addr = super::virt_boot_core_stack_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} + +/// The MMIO remap pages. +pub fn virt_mmio_remap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::mmio_remap_size()); + + let start_page_addr = super::virt_mmio_remap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Add mapping records for the kernel binary. +/// +/// The actual translation table entries for the kernel binary are generated using the offline +/// `translation table tool` and patched into the kernel binary. This function just adds the mapping +/// record entries. +pub fn kernel_add_mapping_records_for_precomputed() { + let virt_code_region = virt_code_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel code and RO data", + &virt_code_region, + &kernel_virt_to_phys_region(virt_code_region), + &kernel_page_attributes(virt_code_region.start_page_addr()), + ); + + let virt_data_region = virt_data_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel data and bss", + &virt_data_region, + &kernel_virt_to_phys_region(virt_data_region), + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); + + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", + &virt_boot_core_stack_region, + &kernel_virt_to_phys_region(virt_boot_core_stack_region), + &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), + ); +} diff --git a/18_backtrace/kernel/src/common.rs b/18_backtrace/kernel/src/common.rs new file mode 100644 index 000000000..2ad7e4c1e --- /dev/null +++ b/18_backtrace/kernel/src/common.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Check if a value is aligned to a given size. +#[inline(always)] +pub const fn is_aligned(value: usize, alignment: usize) -> bool { + assert!(alignment.is_power_of_two()); + + (value & (alignment - 1)) == 0 +} + +/// Align down. +#[inline(always)] +pub const fn align_down(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + value & !(alignment - 1) +} + +/// Align up. +#[inline(always)] +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + (value + alignment - 1) & !(alignment - 1) +} + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/18_backtrace/kernel/src/console.rs b/18_backtrace/kernel/src/console.rs new file mode 100644 index 000000000..f03634649 --- /dev/null +++ b/18_backtrace/kernel/src/console.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod null_console; + +use crate::synchronization; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.read(|con| *con) +} diff --git a/18_backtrace/kernel/src/console/null_console.rs b/18_backtrace/kernel/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/18_backtrace/kernel/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/18_backtrace/kernel/src/cpu.rs b/18_backtrace/kernel/src/cpu.rs new file mode 100644 index 000000000..8716a918b --- /dev/null +++ b/18_backtrace/kernel/src/cpu.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +pub mod smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/18_backtrace/kernel/src/cpu/boot.rs b/18_backtrace/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/18_backtrace/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/18_backtrace/kernel/src/cpu/smp.rs b/18_backtrace/kernel/src/cpu/smp.rs new file mode 100644 index 000000000..de612d589 --- /dev/null +++ b/18_backtrace/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff --git a/18_backtrace/kernel/src/driver.rs b/18_backtrace/kernel/src/driver.rs new file mode 100644 index 000000000..2edf8b854 --- /dev/null +++ b/18_backtrace/kernel/src/driver.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner +where + T: 'static, +{ + next_index: usize, + descriptors: [Option>; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager +where + T: 'static, +{ + inner: InitStateLock>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner +where + T: 'static + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + irq_number, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager +where + T: fmt::Display + Copy, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: InitStateLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.write(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.read(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + self.for_each_descriptor(|descriptor| { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff --git a/18_backtrace/kernel/src/exception.rs b/18_backtrace/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/18_backtrace/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/18_backtrace/kernel/src/exception/asynchronous.rs b/18_backtrace/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..2c874dd60 --- /dev/null +++ b/18_backtrace/kernel/src/exception/asynchronous.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff --git a/18_backtrace/kernel/src/exception/asynchronous/null_irq_manager.rs b/18_backtrace/kernel/src/exception/asynchronous/null_irq_manager.rs new file mode 100644 index 000000000..38919ffe4 --- /dev/null +++ b/18_backtrace/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff --git a/18_backtrace/kernel/src/lib.rs b/18_backtrace/kernel/src/lib.rs new file mode 100644 index 000000000..512894f7c --- /dev/null +++ b/18_backtrace/kernel/src/lib.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(generic_const_exprs)] +#![feature(int_roundings)] +#![feature(is_sorted)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(step_trait)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +mod panic_wait; +mod synchronization; + +pub mod backtrace; +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod state; +pub mod symbols; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/18_backtrace/kernel/src/main.rs b/18_backtrace/kernel/src/main.rs new file mode 100644 index 000000000..e41cfaa0d --- /dev/null +++ b/18_backtrace/kernel/src/main.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + +/// Early init code. +/// +/// When this code runs, virtual memory is already enabled. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - Printing will not work until the respective driver's MMIO is remapped. +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + + bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online:"); + memory::mmu::kernel_print_mappings(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + + info!("Echoing input now"); + cpu::wait_forever(); +} diff --git a/18_backtrace/kernel/src/memory.rs b/18_backtrace/kernel/src/memory.rs new file mode 100644 index 000000000..0434b13c7 --- /dev/null +++ b/18_backtrace/kernel/src/memory.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; + +use crate::{bsp, common}; +use core::{ + fmt, + marker::PhantomData, + ops::{Add, Sub}, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Physical {} + +/// Zero-sized type to mark a virtual address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl AddressType for Physical {} +impl AddressType for Virtual {} + +impl Address { + /// Create an instance. + pub const fn new(value: usize) -> Self { + Self { + value, + _address_type: PhantomData, + } + } + + /// Convert to usize. + pub const fn as_usize(self) -> usize { + self.value + } + + /// Align down to page size. + #[must_use] + pub const fn align_down_page(self) -> Self { + let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Align up to page size. + #[must_use] + pub const fn align_up_page(self) -> Self { + let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Checks if the address is page aligned. + pub const fn is_page_aligned(&self) -> bool { + common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) + } + + /// Return the address' offset into the corresponding page. + pub const fn offset_into_page(&self) -> usize { + self.value & bsp::memory::mmu::KernelGranule::MASK + } +} + +impl Add for Address { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: usize) -> Self::Output { + match self.value.checked_add(rhs) { + None => panic!("Overflow on Address::add"), + Some(x) => Self::new(x), + } + } +} + +impl Sub for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: usize) -> Self::Output { + match self.value.checked_sub(rhs) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl Sub> for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Address) -> Self::Output { + match self.value.checked_sub(rhs.value) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl Address { + /// Checks if the address is part of the boot core stack region. + pub fn is_valid_stack_addr(&self) -> bool { + bsp::memory::mmu::virt_boot_core_stack_region().contains(*self) + } + + /// Checks if the address is part of the kernel code region. + pub fn is_valid_code_addr(&self) -> bool { + bsp::memory::mmu::virt_code_region().contains(*self) + } +} + +impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q3: u8 = ((self.value >> 32) & 0xff) as u8; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:02x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q4: u16 = ((self.value >> 48) & 0xffff) as u16; + let q3: u16 = ((self.value >> 32) & 0xffff) as u16; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:04x}_", q4)?; + write!(f, "{:04x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of [Address] methods. + #[kernel_test] + fn address_type_method_sanity() { + let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); + + assert_eq!( + addr.align_down_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE + ); + + assert_eq!( + addr.align_up_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + + assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} diff --git a/18_backtrace/kernel/src/memory/mmu.rs b/18_backtrace/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..404e2a8a9 --- /dev/null +++ b/18_backtrace/kernel/src/memory/mmu.rs @@ -0,0 +1,265 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod mapping_record; +mod page_alloc; +mod translation_table; +mod types; + +use crate::{ + bsp, + memory::{Address, Physical, Virtual}, + synchronization::{self, interface::Mutex}, + warn, +}; +use core::{fmt, num::NonZeroUsize}; + +pub use types::*; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Turns on the MMU for the first time and enables data and instruction caching. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] + type TableStartFromTop; + + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +use interface::MMU; +use synchronization::interface::ReadWriteEx; +use translation_table::interface::TranslationTable; + +/// Map a region in the kernel's translation tables. +/// +/// No input checks done, input is passed through to the architectural implementation. +/// +/// # Safety +/// +/// - See `map_at()`. +/// - Does not prevent aliasing. +unsafe fn kernel_map_at_unchecked( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + + kernel_add_mapping_record(name, virt_region, phys_region, attr); + + Ok(()) +} + +/// Try to translate a kernel virtual address to a physical address. +/// +/// Will only succeed if there exists a valid mapping for the input address. +fn try_kernel_virt_addr_to_phys_addr( + virt_addr: Address, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's mask. + pub const MASK: usize = Self::SIZE - 1; + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +pub fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Add an entry to the mapping info record. +pub fn kernel_add_mapping_record( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) { + if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { + warn!("{}", x); + } +} + +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +/// +/// # Safety +/// +/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + let phys_region = MemoryRegion::from(*mmio_descriptor); + let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); + + // Check if an identical region has been mapped for another driver. If so, reuse it. + let virt_addr = if let Some(addr) = + mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) + { + addr + // Otherwise, allocate a new region and map it. + } else { + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, + }; + + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + virt_region.start_addr() + }; + + Ok(virt_addr + offset_into_start_page) +} + +/// Try to translate a kernel virtual page address to a physical page address. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_virt_page_addr_to_phys_page_addr( + virt_page_addr: PageAddress, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) +} + +/// Try to get the attributes of a kernel page. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_page_attributes( + virt_page_addr: PageAddress, +) -> Result { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_page_attributes(virt_page_addr)) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() +} + +/// Enable the MMU and data + instruction caching. +/// +/// # Safety +/// +/// - Crucial function during kernel init. Changes the the complete memory view of the processor. +#[inline(always)] +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) +} diff --git a/18_backtrace/kernel/src/memory/mmu/mapping_record.rs b/18_backtrace/kernel/src/memory/mmu/mapping_record.rs new file mode 100644 index 000000000..0e0792201 --- /dev/null +++ b/18_backtrace/kernel/src/memory/mmu/mapping_record.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + +use super::{ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Type describing a virtual memory mapping. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +struct MappingRecordEntry { + pub users: [Option<&'static str>; 5], + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, + pub attribute_fields: AttributeFields, +} + +struct MappingRecord { + inner: [Option; 12], +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MAPPING_RECORD: InitStateLock = + InitStateLock::new(MappingRecord::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl MappingRecordEntry { + pub fn new( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Self { + Self { + users: [Some(name), None, None, None, None], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), + attribute_fields: *attr, + } + } + + fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { + if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { + return Ok(x); + }; + + Err("Storage for user info exhausted") + } + + pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { + let x = self.find_next_free_user()?; + *x = Some(user); + Ok(()) + } +} + +impl MappingRecord { + pub const fn new() -> Self { + Self { inner: [None; 12] } + } + + fn size(&self) -> usize { + self.inner.iter().filter(|x| x.is_some()).count() + } + + fn sort(&mut self) { + let upper_bound_exclusive = self.size(); + let entries = &mut self.inner[0..upper_bound_exclusive]; + + if !entries.is_sorted_by_key(|item| item.unwrap().virt_start_addr) { + entries.sort_unstable_by_key(|item| item.unwrap().virt_start_addr) + } + } + + fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { + if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { + return Ok(x); + } + + Err("Storage for mapping info exhausted") + } + + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() + .filter_map(|x| x.as_mut()) + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { + return false; + } + + if x.num_pages != phys_region.num_pages() { + return false; + } + + true + }) + } + + pub fn add( + &mut self, + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + let x = self.find_next_free()?; + + *x = Some(MappingRecordEntry::new( + name, + virt_region, + phys_region, + attr, + )); + + self.sort(); + + Ok(()) + } + + pub fn print(&self) { + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", + "Virtual", "Physical", "Size", "Attr", "Entity" + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + + for i in self.inner.iter().flatten() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match i.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if i.attribute_fields.execute_never { + "XN" + } else { + "X" + }; + + info!( + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, + phys_end_inclusive, + size, + unit, + attr, + acc_p, + xn, + i.users[0].unwrap() + ); + + for k in i.users[1..].iter() { + if let Some(additional_user) = *k { + info!( + " | {}", + additional_user + ); + } + } + } + + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +/// Add an entry to the mapping info record. +pub fn kernel_add( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) +} + +pub fn kernel_find_and_insert_mmio_duplicate( + mmio_descriptor: &MMIODescriptor, + new_user: &'static str, +) -> Option> { + let phys_region: MemoryRegion = (*mmio_descriptor).into(); + + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + + if let Err(x) = dup.add_user(new_user) { + warn!("{}", x); + } + + Some(dup.virt_start_addr) + }) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print() { + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} diff --git a/18_backtrace/kernel/src/memory/mmu/page_alloc.rs b/18_backtrace/kernel/src/memory/mmu/page_alloc.rs new file mode 100644 index 000000000..344afd200 --- /dev/null +++ b/18_backtrace/kernel/src/memory/mmu/page_alloc.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Page allocation. + +use super::MemoryRegion; +use crate::{ + memory::{AddressType, Virtual}, + synchronization::IRQSafeNullLock, + warn, +}; +use core::num::NonZeroUsize; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A page allocator that can be lazyily initialized. +pub struct PageAllocator { + pool: Option>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = + IRQSafeNullLock::new(PageAllocator::new()); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's MMIO virtual address allocator. +pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { + &KERNEL_MMIO_VA_ALLOCATOR +} + +impl PageAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { pool: None } + } + + /// Initialize the allocator. + pub fn init(&mut self, pool: MemoryRegion) { + if self.pool.is_some() { + warn!("Already initialized"); + return; + } + + self.pool = Some(pool); + } + + /// Allocate a number of pages. + pub fn alloc( + &mut self, + num_requested_pages: NonZeroUsize, + ) -> Result, &'static str> { + if self.pool.is_none() { + return Err("Allocator not initialized"); + } + + self.pool + .as_mut() + .unwrap() + .take_first_n_pages(num_requested_pages) + } +} diff --git a/18_backtrace/kernel/src/memory/mmu/translation_table.rs b/18_backtrace/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..341ffc5c8 --- /dev/null +++ b/18_backtrace/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +use super::{AttributeFields, MemoryRegion}; +use crate::memory::{Address, Physical, Virtual}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(target_arch = "aarch64")] +pub use arch_translation_table::FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Translation table interfaces. +pub mod interface { + use crate::memory::mmu::PageAddress; + + use super::*; + + /// Translation table operations. + pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self) -> Result<(), &'static str>; + + /// Map the given virtual memory region to the given physical memory region. + /// + /// # Safety + /// + /// - Using wrong attributes can cause multiple issues of different nature in the system. + /// - It is not required that the architectural implementation prevents aliasing. That is, + /// mapping to the same physical memory using multiple virtual addresses, which would + /// break Rust's ownership assumptions. This should be protected against in the kernel's + /// generic MMU code. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; + + /// Try to translate a virtual page address to a physical page address. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str>; + + /// Try to get the attributes of a page. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result; + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str>; + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use arch_translation_table::MinSizeTranslationTable; + use interface::TranslationTable; + use test_macros::kernel_test; + + /// Sanity checks for the TranslationTable implementation. + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. + let mut tables = MinSizeTranslationTable::new_for_runtime(); + + assert_eq!(tables.init(), Ok(())); + + let virt_end_exclusive_page_addr: PageAddress = PageAddress::MAX; + let virt_start_page_addr: PageAddress = + virt_end_exclusive_page_addr.checked_offset(-5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + + let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + + assert_eq!( + tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), + Ok(phys_start_page_addr) + ); + + assert_eq!( + tables.try_page_attributes(virt_start_page_addr.checked_offset(-1).unwrap()), + Err("Page marked invalid") + ); + + assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); + + let virt_addr = virt_start_page_addr.into_inner() + 0x100; + let phys_addr = phys_start_page_addr.into_inner() + 0x100; + assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); + } +} diff --git a/18_backtrace/kernel/src/memory/mmu/types.rs b/18_backtrace/kernel/src/memory/mmu/types.rs new file mode 100644 index 000000000..f6ac8d598 --- /dev/null +++ b/18_backtrace/kernel/src/memory/mmu/types.rs @@ -0,0 +1,378 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + +use crate::{ + bsp, common, + memory::{Address, AddressType, Physical}, +}; +use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct PageAddress { + inner: Address, +} + +/// A type that describes a region of memory in quantities of pages. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// An MMIO descriptor for use in device drivers. +#[derive(Copy, Clone)] +pub struct MMIODescriptor { + start_addr: Address, + end_addr_exclusive: Address, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------ +// PageAddress +//------------------------------------------------------------------------------ +impl PageAddress { + /// The largest value that can be represented by this type. + pub const MAX: Self = PageAddress { + inner: Address::new(usize::MAX).align_down_page(), + }; + + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + } + + /// Calculates the offset from the page address. + /// + /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * + /// page_size`. + pub fn checked_offset(self, count: isize) -> Option { + if count == 0 { + return Some(self); + } + + let delta = count + .unsigned_abs() + .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; + let result = if count.is_positive() { + self.inner.as_usize().checked_add(delta)? + } else { + self.inner.as_usize().checked_sub(delta)? + }; + + Some(Self { + inner: Address::new(result), + }) + } +} + +impl From for PageAddress { + fn from(addr: usize) -> Self { + assert!( + common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), + "Input usize not page aligned" + ); + + Self { + inner: Address::new(addr), + } + } +} + +impl From> for PageAddress { + fn from(addr: Address) -> Self { + assert!(addr.is_page_aligned(), "Input Address not page aligned"); + + Self { inner: addr } + } +} + +impl Step for PageAddress { + fn steps_between(start: &Self, end: &Self) -> Option { + if start > end { + return None; + } + + // Since start <= end, do unchecked arithmetic. + Some( + (end.inner.as_usize() - start.inner.as_usize()) + >> bsp::memory::mmu::KernelGranule::SHIFT, + ) + } + + fn forward_checked(start: Self, count: usize) -> Option { + start.checked_offset(count as isize) + } + + fn backward_checked(start: Self, count: usize) -> Option { + start.checked_offset(-(count as isize)) + } +} + +//------------------------------------------------------------------------------ +// MemoryRegion +//------------------------------------------------------------------------------ +impl MemoryRegion { + /// Create an instance. + pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { + assert!(start <= end_exclusive); + + Self { + start, + end_exclusive, + } + } + + fn as_range(&self) -> Range> { + self.into_iter() + } + + /// Returns the start page address. + pub fn start_page_addr(&self) -> PageAddress { + self.start + } + + /// Returns the start address. + pub fn start_addr(&self) -> Address { + self.start.into_inner() + } + + /// Returns the exclusive end page address. + pub fn end_exclusive_page_addr(&self) -> PageAddress { + self.end_exclusive + } + + /// Returns the exclusive end page address. + pub fn end_inclusive_page_addr(&self) -> PageAddress { + self.end_exclusive.checked_offset(-1).unwrap() + } + + /// Checks if self contains an address. + pub fn contains(&self, addr: Address) -> bool { + let page_addr = PageAddress::from(addr.align_down_page()); + self.as_range().contains(&page_addr) + } + + /// Checks if there is an overlap with another memory region. + pub fn overlaps(&self, other_region: &Self) -> bool { + let self_range = self.as_range(); + + self_range.contains(&other_region.start_page_addr()) + || self_range.contains(&other_region.end_inclusive_page_addr()) + } + + /// Returns the number of pages contained in this region. + pub fn num_pages(&self) -> usize { + PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() + } + + /// Returns the size in bytes of this region. + pub fn size(&self) -> usize { + // Invariant: start <= end_exclusive, so do unchecked arithmetic. + let end_exclusive = self.end_exclusive.into_inner().as_usize(); + let start = self.start.into_inner().as_usize(); + + end_exclusive - start + } + + /// Splits the MemoryRegion like: + /// + /// -------------------------------------------------------------------------------- + /// | | | | | | | | | | | | | | | | | | | + /// -------------------------------------------------------------------------------- + /// ^ ^ ^ + /// | | | + /// left_start left_end_exclusive | + /// | + /// ^ | + /// | | + /// right_start right_end_exclusive + /// + /// Left region is returned to the caller. Right region is the new region for this struct. + pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { + let count: usize = num_pages.into(); + + let left_end_exclusive = self.start.checked_offset(count as isize); + let left_end_exclusive = match left_end_exclusive { + None => return Err("Overflow while calculating left_end_exclusive"), + Some(x) => x, + }; + + if left_end_exclusive > self.end_exclusive { + return Err("Not enough free pages"); + } + + let allocation = Self { + start: self.start, + end_exclusive: left_end_exclusive, + }; + self.start = left_end_exclusive; + + Ok(allocation) + } +} + +impl IntoIterator for MemoryRegion { + type Item = PageAddress; + type IntoIter = Range; + + fn into_iter(self) -> Self::IntoIter { + Range { + start: self.start, + end: self.end_exclusive, + } + } +} + +impl From for MemoryRegion { + fn from(desc: MMIODescriptor) -> Self { + let start = PageAddress::from(desc.start_addr.align_down_page()); + let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); + + Self { + start, + end_exclusive, + } + } +} + +//------------------------------------------------------------------------------ +// MMIODescriptor +//------------------------------------------------------------------------------ + +impl MMIODescriptor { + /// Create an instance. + pub const fn new(start_addr: Address, size: usize) -> Self { + assert!(size > 0); + let end_addr_exclusive = Address::new(start_addr.as_usize() + size); + + Self { + start_addr, + end_addr_exclusive, + } + } + + /// Return the start address. + pub const fn start_addr(&self) -> Address { + self.start_addr + } + + /// Return the exclusive end address. + pub fn end_addr_exclusive(&self) -> Address { + self.end_addr_exclusive + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::Virtual; + use test_macros::kernel_test; + + /// Sanity of [PageAddress] methods. + #[kernel_test] + fn pageaddress_type_method_sanity() { + let page_addr: PageAddress = + PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); + + assert_eq!( + page_addr.checked_offset(-2), + Some(PageAddress::::from(0)) + ); + + assert_eq!( + page_addr.checked_offset(2), + Some(PageAddress::::from( + bsp::memory::mmu::KernelGranule::SIZE * 4 + )) + ); + + assert_eq!( + PageAddress::::from(0).checked_offset(0), + Some(PageAddress::::from(0)) + ); + assert_eq!(PageAddress::::from(0).checked_offset(-1), None); + + let max_page_addr = Address::::new(usize::MAX).align_down_page(); + assert_eq!( + PageAddress::::from(max_page_addr).checked_offset(1), + None + ); + + let zero = PageAddress::::from(0); + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); + } + + /// Sanity of [MemoryRegion] methods. + #[kernel_test] + fn memoryregion_type_method_sanity() { + let zero = PageAddress::::from(0); + let zero_region = MemoryRegion::new(zero, zero); + assert_eq!(zero_region.num_pages(), 0); + assert_eq!(zero_region.size(), 0); + + let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); + let one_region = MemoryRegion::new(zero, one); + assert_eq!(one_region.num_pages(), 1); + assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); + + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + let mut three_region = MemoryRegion::new(zero, three); + assert!(three_region.contains(zero.into_inner())); + assert!(!three_region.contains(three.into_inner())); + assert!(three_region.overlaps(&one_region)); + + let allocation = three_region + .take_first_n_pages(NonZeroUsize::new(2).unwrap()) + .unwrap(); + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + + for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE + ); + } + } +} diff --git a/18_backtrace/kernel/src/panic_wait.rs b/18_backtrace/kernel/src/panic_wait.rs new file mode 100644 index 000000000..389eb2c88 --- /dev/null +++ b/18_backtrace/kernel/src/panic_wait.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{backtrace, cpu, exception, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + backtrace::Backtrace + ); + + _panic_exit() +} diff --git a/18_backtrace/kernel/src/print.rs b/18_backtrace/kernel/src/print.rs new file mode 100644 index 000000000..8e3030466 --- /dev/null +++ b/18_backtrace/kernel/src/print.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff --git a/18_backtrace/kernel/src/state.rs b/18_backtrace/kernel/src/state.rs new file mode 100644 index 000000000..becdd1b65 --- /dev/null +++ b/18_backtrace/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create an instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff --git a/18_backtrace/kernel/src/symbols.rs b/18_backtrace/kernel/src/symbols.rs new file mode 100644 index 000000000..fdc1d084c --- /dev/null +++ b/18_backtrace/kernel/src/symbols.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Debug symbol support. + +use crate::memory::{Address, Virtual}; +use core::{cell::UnsafeCell, slice}; +use debug_symbol_types::Symbol; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbol from the linker script. +extern "Rust" { + static __kernel_symbols_start: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// This will be patched to the correct value by the "kernel symbols tool" after linking. This given +/// value here is just a (safe) dummy. +#[no_mangle] +static NUM_KERNEL_SYMBOLS: u64 = 0; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn kernel_symbol_section_virt_start_addr() -> Address { + Address::new(unsafe { __kernel_symbols_start.get() as usize }) +} + +fn num_kernel_symbols() -> usize { + unsafe { + // Read volatile is needed here to prevent the compiler from optimizing NUM_KERNEL_SYMBOLS + // away. + core::ptr::read_volatile(&NUM_KERNEL_SYMBOLS as *const u64) as usize + } +} + +fn kernel_symbols_slice() -> &'static [Symbol] { + let ptr = kernel_symbol_section_virt_start_addr().as_usize() as *const Symbol; + + unsafe { slice::from_raw_parts(ptr, num_kernel_symbols()) } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Retrieve the symbol corresponding to a virtual address, if any. +pub fn lookup_symbol(addr: Address) -> Option<&'static Symbol> { + kernel_symbols_slice() + .iter() + .find(|&i| i.contains(addr.as_usize())) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of symbols module. + #[kernel_test] + fn symbols_sanity() { + let first_sym = lookup_symbol(Address::new( + crate::common::is_aligned as *const usize as usize, + )) + .unwrap() + .name(); + + assert_eq!(first_sym, "libkernel::common::is_aligned"); + + let second_sym = lookup_symbol(Address::new(crate::version as *const usize as usize)) + .unwrap() + .name(); + + assert_eq!(second_sym, "libkernel::version"); + } +} diff --git a/18_backtrace/kernel/src/synchronization.rs b/18_backtrace/kernel/src/synchronization.rs new file mode 100644 index 000000000..5740b63e5 --- /dev/null +++ b/18_backtrace/kernel/src/synchronization.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use crate::{exception, state}; + +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } +} diff --git a/18_backtrace/kernel/src/time.rs b/18_backtrace/kernel/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/18_backtrace/kernel/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/18_backtrace/kernel/tests/00_console_sanity.rb b/18_backtrace/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/18_backtrace/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/18_backtrace/kernel/tests/00_console_sanity.rs b/18_backtrace/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..682ea9b8a --- /dev/null +++ b/18_backtrace/kernel/tests/00_console_sanity.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, memory, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/18_backtrace/kernel/tests/01_timer_sanity.rs b/18_backtrace/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..1581a02e0 --- /dev/null +++ b/18_backtrace/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, memory, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/18_backtrace/kernel/tests/02_exception_sync_page_fault.rs b/18_backtrace/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..09d177981 --- /dev/null +++ b/18_backtrace/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + info!("Writing to bottom of address space to address 1 GiB..."); + let big_addr: u64 = 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/18_backtrace/kernel/tests/03_exception_restore_sanity.rb b/18_backtrace/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/18_backtrace/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/18_backtrace/kernel/tests/03_exception_restore_sanity.rs b/18_backtrace/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..1a3029112 --- /dev/null +++ b/18_backtrace/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/18_backtrace/kernel/tests/04_exception_irq_sanity.rs b/18_backtrace/kernel/tests/04_exception_irq_sanity.rs new file mode 100644 index 000000000..fcace8979 --- /dev/null +++ b/18_backtrace/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception, memory}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + memory::init(); + bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} diff --git a/18_backtrace/kernel/tests/05_backtrace_sanity.rb b/18_backtrace/kernel/tests/05_backtrace_sanity.rb new file mode 100644 index 000000000..243e2fc86 --- /dev/null +++ b/18_backtrace/kernel/tests/05_backtrace_sanity.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that panic produces a backtrace. +class PanicBacktraceTest < SubtestBase + def name + 'Panic produces backtrace' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Kernel panic!') + expect_or_raise(qemu_out, 'Backtrace:') + end +end + +# Verify backtrace correctness. +class BacktraceCorrectnessTest < SubtestBase + def name + 'Backtrace is correct' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '| core::panicking::panic') + expect_or_raise(qemu_out, '| _05_backtrace_sanity::nested') + expect_or_raise(qemu_out, '| kernel_init') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [PanicBacktraceTest.new, BacktraceCorrectnessTest.new] +end diff --git a/18_backtrace/kernel/tests/05_backtrace_sanity.rs b/18_backtrace/kernel/tests/05_backtrace_sanity.rs new file mode 100644 index 000000000..66fd0a3e7 --- /dev/null +++ b/18_backtrace/kernel/tests/05_backtrace_sanity.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid frame pointer. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested() { + panic!() +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/18_backtrace/kernel/tests/06_backtrace_invalid_frame.rb b/18_backtrace/kernel/tests/06_backtrace_invalid_frame.rb new file mode 100644 index 000000000..806954682 --- /dev/null +++ b/18_backtrace/kernel/tests/06_backtrace_invalid_frame.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Test detection of invalid frame pointers. +class InvalidFramePointerTest < SubtestBase + def name + 'Detect invalid frame pointer' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, + /Encountered invalid frame pointer \(.*\) during backtrace/) + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [InvalidFramePointerTest.new] +end diff --git a/18_backtrace/kernel/tests/06_backtrace_invalid_frame.rs b/18_backtrace/kernel/tests/06_backtrace_invalid_frame.rs new file mode 100644 index 000000000..38411af69 --- /dev/null +++ b/18_backtrace/kernel/tests/06_backtrace_invalid_frame.rs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid frame pointer. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{backtrace, bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested() { + unsafe { backtrace::corrupt_previous_frame_addr() }; + + panic!() +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/18_backtrace/kernel/tests/07_backtrace_invalid_link.rb b/18_backtrace/kernel/tests/07_backtrace_invalid_link.rb new file mode 100644 index 000000000..6b6f04132 --- /dev/null +++ b/18_backtrace/kernel/tests/07_backtrace_invalid_link.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Test detection of invalid link. +class InvalidLinkTest < SubtestBase + def name + 'Detect invalid link' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, /Link address \(.*\) is not contained in kernel .text section/) + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [InvalidLinkTest.new] +end diff --git a/18_backtrace/kernel/tests/07_backtrace_invalid_link.rs b/18_backtrace/kernel/tests/07_backtrace_invalid_link.rs new file mode 100644 index 000000000..6e0873dd1 --- /dev/null +++ b/18_backtrace/kernel/tests/07_backtrace_invalid_link.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid link. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{backtrace, bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested_2() -> &'static str { + unsafe { backtrace::corrupt_link() }; + libkernel::println!("{}", libkernel::backtrace::Backtrace); + "foo" +} + +#[inline(never)] +fn nested_1() { + libkernel::println!("{}", nested_2()) +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested_1(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/18_backtrace/kernel/tests/boot_test_string.rb b/18_backtrace/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/18_backtrace/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/18_backtrace/kernel/tests/panic_exit_success/mod.rs b/18_backtrace/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/18_backtrace/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/18_backtrace/kernel/tests/panic_wait_forever/mod.rs b/18_backtrace/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/18_backtrace/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/18_backtrace/kernel_symbols.mk b/18_backtrace/kernel_symbols.mk new file mode 100644 index 000000000..d38b7785a --- /dev/null +++ b/18_backtrace/kernel_symbols.mk @@ -0,0 +1,117 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/format.mk +include ../common/docker.mk + +##-------------------------------------------------------------------------------------------------- +## Check for input variables that need be exported by the calling Makefile +##-------------------------------------------------------------------------------------------------- +ifndef KERNEL_SYMBOLS_TOOL_PATH +$(error KERNEL_SYMBOLS_TOOL_PATH is not set) +endif + +ifndef TARGET +$(error TARGET is not set) +endif + +ifndef KERNEL_SYMBOLS_INPUT_ELF +$(error KERNEL_SYMBOLS_INPUT_ELF is not set) +endif + +ifndef KERNEL_SYMBOLS_OUTPUT_ELF +$(error KERNEL_SYMBOLS_OUTPUT_ELF is not set) +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_SYMBOLS_MANIFEST = kernel_symbols/Cargo.toml +KERNEL_SYMBOLS_LINKER_SCRIPT = kernel_symbols/kernel_symbols.ld + +KERNEL_SYMBOLS_RS = $(KERNEL_SYMBOLS_INPUT_ELF)_symbols.rs +KERNEL_SYMBOLS_DEMANGLED_RS = $(shell pwd)/$(KERNEL_SYMBOLS_INPUT_ELF)_symbols_demangled.rs + +KERNEL_SYMBOLS_ELF = target/$(TARGET)/release/kernel_symbols +KERNEL_SYMBOLS_STRIPPED = target/$(TARGET)/release/kernel_symbols_stripped + +# Export for build.rs of kernel_symbols crate. +export KERNEL_SYMBOLS_DEMANGLED_RS + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +GET_SYMBOLS_SECTION_VIRT_ADDR = $(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) \ + --get_symbols_section_virt_addr $(KERNEL_SYMBOLS_OUTPUT_ELF) + +RUSTFLAGS = -C link-arg=--script=$(KERNEL_SYMBOLS_LINKER_SCRIPT) \ + -C link-arg=--section-start=.rodata=$$($(GET_SYMBOLS_SECTION_VIRT_ADDR)) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +COMPILER_ARGS = --target=$(TARGET) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_SYMBOLS_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_SYMBOLS_TOOL = ruby $(KERNEL_SYMBOLS_TOOL_PATH)/main.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all symbols measure_time_start measure_time_finish + +all: measure_time_start symbols measure_time_finish + +symbols: + @cp $(KERNEL_SYMBOLS_INPUT_ELF) $(KERNEL_SYMBOLS_OUTPUT_ELF) + + @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --gen_symbols $(KERNEL_SYMBOLS_OUTPUT_ELF) \ + $(KERNEL_SYMBOLS_RS) + + $(call color_progress_prefix, "Demangling") + @echo Symbol names + @cat $(KERNEL_SYMBOLS_RS) | rustfilt > $(KERNEL_SYMBOLS_DEMANGLED_RS) + + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + + $(call color_progress_prefix, "Stripping") + @echo Symbols ELF file + @$(OBJCOPY_CMD) $(KERNEL_SYMBOLS_ELF) $(KERNEL_SYMBOLS_STRIPPED) + + @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --patch_data $(KERNEL_SYMBOLS_OUTPUT_ELF) \ + $(KERNEL_SYMBOLS_STRIPPED) + +# Note: The following is the only _trivial_ way I could think of that works out of the box on both +# Linux and macOS. Since macOS does not have the %N nanosecond format string option, the +# resolution is restricted to whole seconds. +measure_time_start: + @date +%s > /tmp/kernel_symbols_start.date + +measure_time_finish: + @date +%s > /tmp/kernel_symbols_end.date + + $(call color_progress_prefix, "Finished") + @echo "in $$((`cat /tmp/kernel_symbols_end.date` - `cat /tmp/kernel_symbols_start.date`)).0s" + + @rm /tmp/kernel_symbols_end.date /tmp/kernel_symbols_start.date diff --git a/18_backtrace/kernel_symbols/Cargo.toml b/18_backtrace/kernel_symbols/Cargo.toml new file mode 100644 index 000000000..3407aa7e1 --- /dev/null +++ b/18_backtrace/kernel_symbols/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "kernel_symbols" +version = "0.1.0" +edition = "2021" + +[features] +default = [] +generated_symbols_available = [] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +debug-symbol-types = { path = "../libraries/debug-symbol-types" } diff --git a/18_backtrace/kernel_symbols/build.rs b/18_backtrace/kernel_symbols/build.rs new file mode 100644 index 000000000..5062df444 --- /dev/null +++ b/18_backtrace/kernel_symbols/build.rs @@ -0,0 +1,14 @@ +use std::{env, path::Path}; + +fn main() { + if let Ok(path) = env::var("KERNEL_SYMBOLS_DEMANGLED_RS") { + if Path::new(&path).exists() { + println!("cargo:rustc-cfg=feature=\"generated_symbols_available\"") + } + } + + println!( + "cargo:rerun-if-changed={}", + Path::new("kernel_symbols.ld").display() + ); +} diff --git a/18_backtrace/kernel_symbols/kernel_symbols.ld b/18_backtrace/kernel_symbols/kernel_symbols.ld new file mode 100644 index 000000000..0625f0086 --- /dev/null +++ b/18_backtrace/kernel_symbols/kernel_symbols.ld @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2022 Andre Richter + */ + +SECTIONS +{ + .rodata : { + ASSERT(. > 0xffffffff00000000, "Expected higher half address") + + KEEP(*(.rodata.symbol_desc*)) + . = ALIGN(8); + *(.rodata*) + } +} diff --git a/18_backtrace/kernel_symbols/src/main.rs b/18_backtrace/kernel_symbols/src/main.rs new file mode 100644 index 000000000..38ce18f8f --- /dev/null +++ b/18_backtrace/kernel_symbols/src/main.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Generation of kernel symbols. + +#![no_std] +#![no_main] + +#[cfg(feature = "generated_symbols_available")] +include!(env!("KERNEL_SYMBOLS_DEMANGLED_RS")); + +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unimplemented!() +} diff --git a/18_backtrace/libraries/debug-symbol-types/Cargo.toml b/18_backtrace/libraries/debug-symbol-types/Cargo.toml new file mode 100644 index 000000000..e5b1fd1f5 --- /dev/null +++ b/18_backtrace/libraries/debug-symbol-types/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "debug-symbol-types" +version = "0.1.0" +edition = "2021" diff --git a/18_backtrace/libraries/debug-symbol-types/src/lib.rs b/18_backtrace/libraries/debug-symbol-types/src/lib.rs new file mode 100644 index 000000000..81c897bfa --- /dev/null +++ b/18_backtrace/libraries/debug-symbol-types/src/lib.rs @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Types for implementing debug symbol support. + +#![no_std] + +use core::ops::Range; + +/// A symbol containing a size. +#[repr(C)] +#[derive(Clone)] +pub struct Symbol { + addr_range: Range, + name: &'static str, +} + +impl Symbol { + /// Create an instance. + pub const fn new(start: usize, size: usize, name: &'static str) -> Symbol { + Symbol { + addr_range: Range { + start, + end: start + size, + }, + name, + } + } + + /// Returns true if addr is contained in the range. + pub fn contains(&self, addr: usize) -> bool { + self.addr_range.contains(&addr) + } + + /// Returns the symbol's name. + pub fn name(&self) -> &'static str { + self.name + } + + /// Returns the symbol's size. + pub fn size(&self) -> usize { + self.addr_range.end - self.addr_range.start + } +} diff --git a/18_backtrace/libraries/test-macros/Cargo.toml b/18_backtrace/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/18_backtrace/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/18_backtrace/libraries/test-macros/src/lib.rs b/18_backtrace/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/18_backtrace/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/18_backtrace/libraries/test-types/Cargo.toml b/18_backtrace/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/18_backtrace/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/18_backtrace/libraries/test-types/src/lib.rs b/18_backtrace/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/18_backtrace/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/18_backtrace/tools/kernel_symbols_tool/cmds.rb b/18_backtrace/tools/kernel_symbols_tool/cmds.rb new file mode 100644 index 000000000..c43acb24c --- /dev/null +++ b/18_backtrace/tools/kernel_symbols_tool/cmds.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +def generate_symbols(kernel_elf, output_file) + File.open(output_file, 'w') do |file| + header = <<~HEREDOC + use debug_symbol_types::Symbol; + + # [no_mangle] + # [link_section = ".rodata.symbol_desc"] + static KERNEL_SYMBOLS: [Symbol; #{kernel_elf.num_symbols}] = [ + HEREDOC + + file.write(header) + kernel_elf.symbols.each do |sym| + value = sym.header.st_value + size = sym.header.st_size + name = sym.name + + file.write(" Symbol::new(#{value}, #{size}, \"#{name}\"),\n") + end + file.write("];\n") + end +end + +def get_symbols_section_virt_addr(kernel_elf) + kernel_elf.kernel_symbols_section_virt_addr +end + +def patch_symbol_data(kernel_elf, symbols_blob_path) + symbols_blob = File.binread(symbols_blob_path) + + raise if symbols_blob.size > kernel_elf.kernel_symbols_section_size + + File.binwrite(kernel_elf.path, File.binread(symbols_blob_path), + kernel_elf.kernel_symbols_section_offset_in_file) +end + +def patch_num_symbols(kernel_elf) + num_packed = [kernel_elf.num_symbols].pack('Q<*') # "Q" == uint64_t, "<" == little endian + File.binwrite(kernel_elf.path, num_packed, kernel_elf.num_kernel_symbols_offset_in_file) +end diff --git a/18_backtrace/tools/kernel_symbols_tool/kernel_elf.rb b/18_backtrace/tools/kernel_symbols_tool/kernel_elf.rb new file mode 100644 index 000000000..32b5460aa --- /dev/null +++ b/18_backtrace/tools/kernel_symbols_tool/kernel_elf.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + attr_reader :path + + def initialize(kernel_elf_path, kernel_symbols_section, num_kernel_symbols) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + + @path = kernel_elf_path + fetch_values(kernel_symbols_section, num_kernel_symbols) + end + + private + + def fetch_values(kernel_symbols_section, num_kernel_symbols) + sym = @symtab_section.symbol_by_name(num_kernel_symbols) + raise "Symbol \"#{num_kernel_symbols}\" not found" if sym.nil? + + @num_kernel_symbols = sym + + section = @elf.section_by_name(kernel_symbols_section) + raise "Section \"#{kernel_symbols_section}\" not found" if section.nil? + + @kernel_symbols_section = section + end + + def num_kernel_symbols_virt_addr + @num_kernel_symbols.header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + public + + def symbols + non_zero_symbols = @symtab_section.symbols.reject { |sym| sym.header.st_size.zero? } + non_zero_symbols.sort_by { |sym| sym.header.st_value } + end + + def num_symbols + symbols.size + end + + def kernel_symbols_section_virt_addr + @kernel_symbols_section.header.sh_addr.to_i + end + + def kernel_symbols_section_size + @kernel_symbols_section.header.sh_size.to_i + end + + def kernel_symbols_section_offset_in_file + virt_addr_to_file_offset(kernel_symbols_section_virt_addr) + end + + def num_kernel_symbols_offset_in_file + virt_addr_to_file_offset(num_kernel_symbols_virt_addr) + end +end diff --git a/18_backtrace/tools/kernel_symbols_tool/main.rb b/18_backtrace/tools/kernel_symbols_tool/main.rb new file mode 100755 index 000000000..899f96464 --- /dev/null +++ b/18_backtrace/tools/kernel_symbols_tool/main.rb @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'kernel_elf' +require_relative 'cmds' + +KERNEL_SYMBOLS_SECTION = '.kernel_symbols' +NUM_KERNEL_SYMBOLS = 'NUM_KERNEL_SYMBOLS' + +cmd = ARGV[0] + +kernel_elf_path = ARGV[1] +kernel_elf = KernelELF.new(kernel_elf_path, KERNEL_SYMBOLS_SECTION, NUM_KERNEL_SYMBOLS) + +case cmd +when '--gen_symbols' + output_file = ARGV[2] + + print 'Generating'.rjust(12).green.bold + puts ' Symbols source file' + + generate_symbols(kernel_elf, output_file) +when '--get_symbols_section_virt_addr' + addr = get_symbols_section_virt_addr(kernel_elf) + + puts "0x#{addr.to_s(16)}" +when '--patch_data' + symbols_blob_path = ARGV[2] + num_symbols = kernel_elf.num_symbols + + print 'Patching'.rjust(12).green.bold + puts " Symbols blob and number of symbols (#{num_symbols}) into ELF" + + patch_symbol_data(kernel_elf, symbols_blob_path) + patch_num_symbols(kernel_elf) +else + raise +end diff --git a/18_backtrace/tools/translation_table_tool/arch.rb b/18_backtrace/tools/translation_table_tool/arch.rb new file mode 100644 index 000000000..053cac194 --- /dev/null +++ b/18_backtrace/tools/translation_table_tool/arch.rb @@ -0,0 +1,314 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Bitfield manipulation. +class BitField + def initialize + @value = 0 + end + + def self.attr_bitfield(name, offset, num_bits) + define_method("#{name}=") do |bits| + mask = (2**num_bits) - 1 + + raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? + + # Clear bitfield + @value &= ~(mask << offset) + + # Set it + @value |= (bits << offset) + end + end + + def to_i + @value + end + + def size_in_byte + 8 + end +end + +# An array class that knows its memory location. +class CArray < Array + attr_reader :phys_start_addr + + def initialize(phys_start_addr, size, &block) + @phys_start_addr = phys_start_addr + + super(size, &block) + end + + def size_in_byte + inject(0) { |sum, n| sum + n.size_in_byte } + end +end + +#--------------------------------------------------------------------------------------------------- +# Arch:: +#--------------------------------------------------------------------------------------------------- +module Arch +#--------------------------------------------------------------------------------------------------- +# Arch::ARMv8 +#--------------------------------------------------------------------------------------------------- +module ARMv8 +# ARMv8 Table Descriptor. +class Stage1TableDescriptor < BitField + module NextLevelTableAddr + OFFSET = 16 + NUMBITS = 32 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + BLOCK = 0 + TABLE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def next_level_table_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__next_level_table_addr = addr + end + + private :__next_level_table_addr= +end + +# ARMv8 level 3 page descriptor. +class Stage1PageDescriptor < BitField + module UXN + OFFSET = 54 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module PXN + OFFSET = 53 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module OutputAddr + OFFSET = 16 + NUMBITS = 32 + end + + module AF + OFFSET = 10 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module SH + OFFSET = 8 + NUMBITS = 2 + + INNER_SHAREABLE = 0b11 + end + + module AP + OFFSET = 6 + NUMBITS = 2 + + RW_EL1 = 0b00 + RO_EL1 = 0b10 + end + + module AttrIndx + OFFSET = 2 + NUMBITS = 3 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + RESERVED_INVALID = 0 + PAGE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) + attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) + attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) + attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) + attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) + attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) + attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def output_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__output_addr = addr + end + + private :__output_addr= +end + +# Translation table representing the structure defined in translation_table.rs. +class TranslationTable + module MAIR + NORMAL = 1 + end + + def initialize + do_sanity_checks + + num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT + + @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) + + @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte + @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) + + populate_lvl2_entries + end + + def map_at(virt_region, phys_region, attributes) + return if virt_region.empty? + + raise if virt_region.size != phys_region.size + raise if phys_region.last > BSP.phys_addr_space_end_page + + virt_region.zip(phys_region).each do |virt_page, phys_page| + desc = page_descriptor_from(virt_page) + set_lvl3_entry(desc, phys_page, attributes) + end + end + + def to_binary + data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) + data.pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr_binary + [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr + @lvl2_phys_start_addr + end + + private + + def do_sanity_checks + raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE + raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? + end + + def new_lvl3(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + temp = CArray.new(start_addr, 8192) do + Stage1PageDescriptor.new + end + start_addr += temp.size_in_byte + + temp + end + end + + def new_lvl2(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + Stage1TableDescriptor.new + end + end + + def populate_lvl2_entries + @lvl2.each_with_index do |descriptor, i| + descriptor.next_level_table_addr = @lvl3[i].phys_start_addr + descriptor.type = Stage1TableDescriptor::Type::TABLE + descriptor.valid = Stage1TableDescriptor::Valid::TRUE + end + end + + def lvl2_lvl3_index_from(addr) + addr -= BSP.kernel_virt_start_addr + + lvl2_index = addr >> Granule512MiB::SHIFT + lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT + + raise unless lvl2_index < @lvl2.size + + [lvl2_index, lvl3_index] + end + + def page_descriptor_from(virt_addr) + lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) + + @lvl3[lvl2_index][lvl3_index] + end + + # rubocop:disable Metrics/MethodLength + def set_attributes(desc, attributes) + case attributes.mem_attributes + when :CacheableDRAM + desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE + desc.attr_indx = MAIR::NORMAL + else + raise 'Invalid input' + end + + desc.ap = case attributes.acc_perms + when :ReadOnly + Stage1PageDescriptor::AP::RO_EL1 + when :ReadWrite + Stage1PageDescriptor::AP::RW_EL1 + else + raise 'Invalid input' + + end + + desc.pxn = if attributes.execute_never + Stage1PageDescriptor::PXN::TRUE + else + Stage1PageDescriptor::PXN::FALSE + end + + desc.uxn = Stage1PageDescriptor::UXN::TRUE + end + # rubocop:enable Metrics/MethodLength + + def set_lvl3_entry(desc, output_addr, attributes) + desc.output_addr = output_addr + desc.af = Stage1PageDescriptor::AF::TRUE + desc.type = Stage1PageDescriptor::Type::PAGE + desc.valid = Stage1PageDescriptor::Valid::TRUE + + set_attributes(desc, attributes) + end +end +end +end diff --git a/18_backtrace/tools/translation_table_tool/bsp.rb b/18_backtrace/tools/translation_table_tool/bsp.rb new file mode 100644 index 000000000..5887d7745 --- /dev/null +++ b/18_backtrace/tools/translation_table_tool/bsp.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Raspberry Pi 3 + 4 +class RaspberryPi + attr_reader :kernel_granule, :kernel_virt_addr_space_size, :kernel_virt_start_addr + + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + + def initialize + @kernel_granule = Granule64KiB + + @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') + @kernel_virt_start_addr = KERNEL_ELF.symbol_value('__kernel_virt_start_addr') + + @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') + @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( + 'PHYS_KERNEL_TABLES_BASE_ADDR' + ) + end + + def phys_addr_of_kernel_tables + KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) + end + + def kernel_tables_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) + end + + def phys_kernel_tables_base_addr_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) + end + + def phys_addr_space_end_page + x = MEMORY_SRC.grep(/pub const END/) + x = case BSP_TYPE + when :rpi3 + x[0] + when :rpi4 + x[1] + else + raise + end + + # Extract the hex literal with underscores like 0x0123_abcd. + x = x.scan(/0x[\h_]*/)[0] + + # Further remove x and _ and convert to int. + x.scan(/\h+/).join.to_i(16) + end +end diff --git a/18_backtrace/tools/translation_table_tool/generic.rb b/18_backtrace/tools/translation_table_tool/generic.rb new file mode 100644 index 000000000..941e2226f --- /dev/null +++ b/18_backtrace/tools/translation_table_tool/generic.rb @@ -0,0 +1,189 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +module Granule64KiB + SIZE = 64 * 1024 + SHIFT = Math.log2(SIZE).to_i +end + +module Granule512MiB + SIZE = 512 * 1024 * 1024 + SHIFT = Math.log2(SIZE).to_i + MASK = SIZE - 1 +end + +# Monkey-patch Integer with some helper functions. +class Integer + def power_of_two? + self[0].zero? + end + + def aligned?(alignment) + raise unless alignment.power_of_two? + + (self & (alignment - 1)).zero? + end + + def align_up(alignment) + raise unless alignment.power_of_two? + + (self + alignment - 1) & ~(alignment - 1) + end + + def to_hex_underscore(with_leading_zeros: false) + fmt = with_leading_zeros ? '%016x' : '%x' + value = format(fmt, self).to_s.reverse.scan(/.{4}|.+/).join('_').reverse + + format('0x%s', value) + end +end + +# An array where each value is the start address of a Page. +class MemoryRegion < Array + def initialize(start_addr, size, granule_size) + raise unless start_addr.aligned?(granule_size) + raise unless size.positive? + raise unless (size % granule_size).zero? + + num_pages = size / granule_size + super(num_pages) do |i| + (i * granule_size) + start_addr + end + end +end + +# Collection of memory attributes. +class AttributeFields + attr_reader :mem_attributes, :acc_perms, :execute_never + + def initialize(mem_attributes, acc_perms, execute_never) + @mem_attributes = mem_attributes + @acc_perms = acc_perms + @execute_never = execute_never + end + + def to_s + x = case @mem_attributes + when :CacheableDRAM + 'C' + else + '?' + end + + y = case @acc_perms + when :ReadWrite + 'RW' + when :ReadOnly + 'RO' + else + '??' + end + + z = @execute_never ? 'XN' : 'X ' + + "#{x} #{y} #{z}" + end +end + +# A container that describes a virt-to-phys region mapping. +class MappingDescriptor + @max_section_name_length = 'Sections'.length + + class << self + attr_accessor :max_section_name_length + + def update_max_section_name_length(length) + @max_section_name_length = [@max_section_name_length, length].max + end + end + + attr_reader :name, :virt_region, :phys_region, :attributes + + def initialize(name, virt_region, phys_region, attributes) + @name = name + @virt_region = virt_region + @phys_region = phys_region + @attributes = attributes + end + + def size_human_readable(size) + if size >= (1024 * 1024) + "#{(size / (1024 * 1024)).to_s.rjust(3)} MiB" + elsif size >= 1024 + "#{(size / 1024).to_s.rjust(3)} KiB" + else + raise + end + end + + def to_s + name = @name.ljust(self.class.max_section_name_length) + virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) + phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) + size = size_human_readable(@virt_region.size * 65_536) + + "#{name} | #{virt_start} | #{phys_start} | #{size} | #{@attributes}" + end + + def self.print_divider + print ' ' + print '-' * max_section_name_length + puts '--------------------------------------------------------------------' + end + + def self.print_header + print_divider + print ' ' + print 'Sections'.center(max_section_name_length) + print ' ' + print 'Virt Start Addr'.center(21) + print ' ' + print 'Phys Start Addr'.center(21) + print ' ' + print 'Size'.center(7) + print ' ' + print 'Attr'.center(7) + puts + print_divider + end +end + +def kernel_map_binary + mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors + + # Generate_mapping_descriptors updates the header being printed with this call. So it must come + # afterwards. + MappingDescriptor.print_header + + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' + puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end + + MappingDescriptor.print_divider +end + +def kernel_patch_tables(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel table struct at ELF file offset ' + puts BSP.kernel_tables_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.to_binary, BSP.kernel_tables_offset_in_file) +end + +def kernel_patch_base_addr(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel tables physical base address start argument to value ' + print TRANSLATION_TABLES.phys_tables_base_addr.to_hex_underscore + print ' at ELF file offset ' + puts BSP.phys_kernel_tables_base_addr_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.phys_tables_base_addr_binary, + BSP.phys_kernel_tables_base_addr_offset_in_file) +end diff --git a/18_backtrace/tools/translation_table_tool/kernel_elf.rb b/18_backtrace/tools/translation_table_tool/kernel_elf.rb new file mode 100644 index 000000000..5ba78d9df --- /dev/null +++ b/18_backtrace/tools/translation_table_tool/kernel_elf.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + SECTION_FLAG_ALLOC = 2 + + def initialize(kernel_elf_path) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + end + + def machine + @elf.machine.to_sym + end + + def symbol_value(symbol_name) + @symtab_section.symbol_by_name(symbol_name).header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_to_phys(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + translation_offset = segment.header.p_vaddr - segment.header.p_paddr + + virt_addr - translation_offset + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + def sections_in_segment(segment) + head = segment.mem_head + tail = segment.mem_tail + + sections = @elf.each_sections.select do |section| + file_offset = section.header.sh_addr + flags = section.header.sh_flags + + file_offset >= head && file_offset < tail && (flags & SECTION_FLAG_ALLOC != 0) + end + + sections.map(&:name).join(' ') + end + + def select_load_segments + @elf.each_segments.select do |segment| + segment.instance_of?(ELFTools::Segments::LoadSegment) + end + end + + def segment_get_acc_perms(segment) + if segment.readable? && segment.writable? + :ReadWrite + elsif segment.readable? + :ReadOnly + else + :Invalid + end + end + + def update_max_section_name_length(descriptors) + MappingDescriptor.update_max_section_name_length(descriptors.map { |i| i.name.size }.max) + end + + def generate_mapping_descriptors + descriptors = select_load_segments.map do |segment| + # Assume each segment is page aligned. + size = segment.mem_size.align_up(BSP.kernel_granule::SIZE) + virt_start_addr = segment.header.p_vaddr + phys_start_addr = segment.header.p_paddr + acc_perms = segment_get_acc_perms(segment) + execute_never = !segment.executable? + section_names = sections_in_segment(segment) + + virt_region = MemoryRegion.new(virt_start_addr, size, BSP.kernel_granule::SIZE) + phys_region = MemoryRegion.new(phys_start_addr, size, BSP.kernel_granule::SIZE) + attributes = AttributeFields.new(:CacheableDRAM, acc_perms, execute_never) + + MappingDescriptor.new(section_names, virt_region, phys_region, attributes) + end + + update_max_section_name_length(descriptors) + descriptors + end +end diff --git a/18_backtrace/tools/translation_table_tool/main.rb b/18_backtrace/tools/translation_table_tool/main.rb new file mode 100755 index 000000000..22ab24fd5 --- /dev/null +++ b/18_backtrace/tools/translation_table_tool/main.rb @@ -0,0 +1,46 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'generic' +require_relative 'kernel_elf' +require_relative 'bsp' +require_relative 'arch' + +BSP_TYPE = ARGV[0].to_sym +kernel_elf_path = ARGV[1] + +start = Time.now + +KERNEL_ELF = KernelELF.new(kernel_elf_path) + +BSP = case BSP_TYPE + when :rpi3, :rpi4 + RaspberryPi.new + else + raise + end + +TRANSLATION_TABLES = case KERNEL_ELF.machine + when :AArch64 + Arch::ARMv8::TranslationTable.new + else + raise + end + +kernel_map_binary +kernel_patch_tables(kernel_elf_path) +kernel_patch_base_addr(kernel_elf_path) + +elapsed = Time.now - start + +print 'Finished'.rjust(12).green.bold +puts " in #{elapsed.round(2)}s" diff --git a/19_kernel_heap/.cargo/config.toml b/19_kernel_heap/.cargo/config.toml new file mode 100644 index 000000000..e34764853 --- /dev/null +++ b/19_kernel_heap/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.'cfg(target_os = "none")'] +runner = "target/kernel_test_runner.sh" diff --git a/19_kernel_heap/.vscode/settings.json b/19_kernel_heap/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/19_kernel_heap/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/19_kernel_heap/Cargo.lock b/19_kernel_heap/Cargo.lock new file mode 100644 index 000000000..0f642903d --- /dev/null +++ b/19_kernel_heap/Cargo.lock @@ -0,0 +1,103 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "debug-symbol-types" +version = "0.1.0" + +[[package]] +name = "kernel_symbols" +version = "0.1.0" +dependencies = [ + "debug-symbol-types", +] + +[[package]] +name = "linked_list_allocator" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e322f259d225fbae43a1b053b2dc6a5968a6bdf8b205f5de684dab485b95030e" + +[[package]] +name = "mingo" +version = "0.19.0" +dependencies = [ + "aarch64-cpu", + "debug-symbol-types", + "linked_list_allocator", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/19_kernel_heap/Cargo.toml b/19_kernel_heap/Cargo.toml new file mode 100644 index 000000000..38eeb1165 --- /dev/null +++ b/19_kernel_heap/Cargo.toml @@ -0,0 +1,11 @@ +[workspace] + +members = [ + "libraries/*", + "kernel", + "kernel_symbols" +] + +[profile.release] +lto = true +debug = true diff --git a/19_kernel_heap/Makefile b/19_kernel_heap/Makefile new file mode 100644 index 000000000..f9704a44c --- /dev/null +++ b/19_kernel_heap/Makefile @@ -0,0 +1,393 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional debug prints. +ifdef DEBUG_PRINTS + FEATURES = --features debug_prints +endif + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -C force-frame-pointers +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -C force-frame-pointers +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP)_$(DEBUG_PRINTS).build_config + +KERNEL_ELF_RAW = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_RAW_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Translation tables +##------------------------------------------------------------------------------ +TT_TOOL_PATH = tools/translation_table_tool + +KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables +KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) + +##------------------------------------------------------------------------------ +## Kernel symbols +##------------------------------------------------------------------------------ +export KERNEL_SYMBOLS_TOOL_PATH = tools/kernel_symbols_tool + +KERNEL_ELF_TTABLES_SYMS = target/$(TARGET)/release/kernel+ttables+symbols + +# Unlike with KERNEL_ELF_RAW, we are not relying on dep-info here. One of the reasons being that the +# name of the generated symbols file varies between runs, which can cause confusion. +KERNEL_ELF_TTABLES_SYMS_DEPS = $(KERNEL_ELF_TTABLES) \ + $(wildcard kernel_symbols/*) \ + $(wildcard $(KERNEL_SYMBOLS_TOOL_PATH)/*) + +export TARGET +export KERNEL_SYMBOLS_INPUT_ELF = $(KERNEL_ELF_TTABLES) +export KERNEL_SYMBOLS_OUTPUT_ELF = $(KERNEL_ELF_TTABLES_SYMS) + +KERNEL_ELF = $(KERNEL_ELF_TTABLES_SYMS) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES += --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +# build-std can be skipped for helper commands that do not rely on correct stack frames and other +# custom compiler options. This results in a huge speedup. +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -Z build-std=core,alloc --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) -Z build-std=core,alloc --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Precompute the kernel translation tables and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) + $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") + @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) + +##------------------------------------------------------------------------------ +## Generate kernel symbols and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES_SYMS): $(KERNEL_ELF_TTABLES_SYMS_DEPS) + $(call color_header, "Generating kernel symbols and patching kernel ELF") + @$(MAKE) --no-print-directory -f kernel_symbols.mk + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF_TTABLES_SYMS) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES_SYMS) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: clean + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb-opt0: RUSTC_MISC_ARGS += -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_ELF_SYMS="$${TEST_ELF}_syms" + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null + + # This overrides the two ENV variables. The other ENV variables that are required as input for + # the .mk file are set already because they are exported by this Makefile and this script is + # started by the same. + KERNEL_SYMBOLS_INPUT_ELF=$$TEST_ELF \ + KERNEL_SYMBOLS_OUTPUT_ELF=$$TEST_ELF_SYMS \ + $(MAKE) --no-print-directory -f kernel_symbols.mk > /dev/null 2>&1 + + $(OBJCOPY_CMD) $$TEST_ELF_SYMS $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/19_kernel_heap/README.md b/19_kernel_heap/README.md new file mode 100644 index 000000000..eedf82c78 --- /dev/null +++ b/19_kernel_heap/README.md @@ -0,0 +1,1472 @@ +# Tutorial 19 - Kernel Heap + +## tl;dr + +- A global heap for the kernel is added, which enables runtime dynamic memory allocation (`Box`, + `Vec`, etc.). +- Heap memory management is using a `linked list allocator`. +- A `debug!` printing macro is added that is only effective when `make` is invoked with + `DEBUG_PRINTS=y`. + +## Table of Contents + +- [Introduction](#introduction) +- [Implementation](#implementation) + - [Debug Prints](#debug-prints) + - [Pre-UART Console Output](#pre-uart-console-output) +- [Test it](#test-it) +- [Diff to previous](#diff-to-previous) + +## Introduction + +The kernel is finally in a good place to add dynamic memory management. The entire kernel runs in +the higher half of the address space by now, and it has decent backtracing support, which can be +leveraged to get rich tracing/debugging support for heap allocations. + +Although it is a vital part of implementing a heap, this tutorial will **not** cover +`allocation/deallocation` of heap memory. Instead, we will re-use [@phil-opp]'s excellent +[`linked_list_allocator`]. The reason is that while dynamic memory allocation algorithms are an +interesting topic, there would not be much added benefit in implementing a `linked list allocator` +of our own, since it would turn out very similar to what Philipp and the other contributors have +implemented already. So we might just re-use that, even more so because it can be plugged seamlessly +into our kernel. [@phil-opp] has also written two great articles on [Heap Allocation] and [Allocator +Designs]. I really recommend to read those now before continuing with this tutorial. + +[@phil-opp]: https://github.com/phil-opp +[`linked_list_allocator`]: https://crates.io/crates/linked_list_allocator +[Heap Allocation]: https://os.phil-opp.com/heap-allocation/ +[Allocator Designs]: https://os.phil-opp.com/allocator-designs/ + +That being said, what this tutorial text will cover is supporting changes for _enabling_ the +linked_list_allocator, and changes to kernel code leveraging the heap. + +## Implementation + +First of all, we need to reserve some DRAM for the heap. Traditionally, this is done in the `linker +script`. We place it after the `.data` section and before the `MMIO remap` section. + +```ld.s + __data_end_exclusive = .; + + /*********************************************************************************************** + * Heap + ***********************************************************************************************/ + __heap_start = .; + .heap (NOLOAD) : + { + . += 16 * 1024 * 1024; + } :segment_heap + __heap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "Heap is not page aligned") + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; +``` + +In the Rust code, the heap properties can now be queried using the added BSP-function +`bsp::memory::mmu::virt_heap_region()`. The heap allocator itself is added in +`src/memory/heap_alloc.rs`. There, we add the `linked_list_allocator`, wrap it into an +`IRQSafeNullock`, and instantiate it the wrapper in a `static`. This way, global access to the +allocator becomes concurrency-safe: + +```rust +use linked_list_allocator::Heap as LinkedListHeap; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A heap allocator that can be lazyily initialized. +pub struct HeapAllocator { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +#[global_allocator] +static KERNEL_HEAP_ALLOCATOR: HeapAllocator = HeapAllocator::new(); +``` + +All that is left to do now is to implement the [`GlobalAlloc`] trait for `HeapAllocator`: + +[`GlobalAlloc`]: https://doc.rust-lang.org/stable/core/alloc/trait.GlobalAlloc.html + +```rust +unsafe impl GlobalAlloc for HeapAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let result = KERNEL_HEAP_ALLOCATOR + .inner + .lock(|inner| inner.allocate_first_fit(layout).ok()); + + match result { + None => core::ptr::null_mut(), + Some(allocation) => { + let ptr = allocation.as_ptr(); + + debug_print_alloc_dealloc("Allocation", ptr, layout); + + ptr + } + } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + KERNEL_HEAP_ALLOCATOR + .inner + .lock(|inner| inner.deallocate(core::ptr::NonNull::new_unchecked(ptr), layout)); + + debug_print_alloc_dealloc("Free", ptr, layout); + } +} +``` + +During kernel init, `kernel_init_heap_allocator()` will be called, which basically points the +wrapped allocator to the heap that we defined earlier: + +```rust +/// Query the BSP for the heap region and initialize the kernel's heap allocator with it. +pub fn kernel_init_heap_allocator() { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + warn!("Already initialized"); + return; + } + + let region = bsp::memory::mmu::virt_heap_region(); + + KERNEL_HEAP_ALLOCATOR.inner.lock(|inner| unsafe { + inner.init(region.start_addr().as_usize() as *mut u8, region.size()) + }); + + INIT_DONE.store(true, Ordering::Relaxed); +} +``` + +That's it already! We can now use `Box`, `Vec` and friends 🥳. + +### Debug Prints + +You might have noticed the `debug_print_alloc_dealloc()` calls in above's snippet. Under the hood, +this function makes use of the `debug!` macro that has been added in this tutorial. This macro will +only print to the console when `make` is invoked with the `ENV` variable `DEBUG_PRINTS` set to +"**y**". As you can see in the following snippet, this enables rich debug output for heap +allocations and deallocations, containing information such as `size`, `start` and `end exclusive` +addresses, as well as a backtrace that shows from where the (de)allocation originated. + +```console +$ DEBUG_PRINTS=y make qemu + +[...] + + Kernel Heap: Allocation + Size: 0x10 (16 Byte) + Start: 0xffff_ffff_c00a_0010 + End excl: 0xffff_ffff_c00a_0020 + + Backtrace: + ---------------------------------------------------------------------------------------------- + Address Function containing address + ---------------------------------------------------------------------------------------------- + 1. ffffffffc000cdf8 | ::write_fmt + 2. ffffffffc000b4f8 | ::alloc + 3. ffffffffc000d940 | libkernel::memory::mmu::mapping_record::kernel_add + 4. ffffffffc000adec | libkernel::bsp::raspberrypi::memory::mmu::kernel_add_mapping_records_for_precomputed + 5. ffffffffc00016ac | kernel_init + ---------------------------------------------------------------------------------------------- + +[ 0.042872] mingo version 0.19.0 +[ 0.043080] Booting on: Raspberry Pi 3 +``` + +### Pre-UART Console Output + +Having a heap allows us to simplify a few modules by switching static-length arrays to the dynamic +`Vec` data structure. Examples are the `interrupt controller drivers` for their handler tables, +`src/memory/mmu/mapping_record.rs` for bookkeeping virtual memory mappings and the `BSP driver +manager` for its instantiated device drivers. + +However, many of those allocations happen already **before** the UART driver comes online. +Therefore, a lot of the (de)allocation debug prints would go into the void with the way pre-UART +prints have been handled so far, which is undesirable. To solve this problem, the kernel's initial +(aka pre-UART) console is now not a `NullConsole` anymore, but a `BufferConsole`. The latter owns a +small static array of `chars`, that records any console prints before the actual UART driver comes +online. Once the UART driver is registered in the kernel to become the default console, the first +thing that is done is to print any buffered records of the `BufferConsole`: + +```rust +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); + + static FIRST_SWITCH: InitStateLock = InitStateLock::new(true); + FIRST_SWITCH.write(|first| { + if *first == true { + *first = false; + + buffer_console::BUFFER_CONSOLE.dump(); + } + }); +} +``` + +`BUFFER_CONSOLE.dump()` just drains its buffer to using the newly registered console. + +## Test it + +If compiled without `DEBUG_PRINTS`, the heap can be observed in the mapping overview and through the +newly added usage statistics: + +```console +$ make chainboot +[...] +Minipush 1.0 + +[MP] ⏳ Waiting for /dev/ttyUSB0 +[MP] ✅ Serial connected +[MP] 🔌 Please power the target now + + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| + + Raspberry Pi 3 + +[ML] Requesting binary +[MP] ⏩ Pushing 320 KiB ======================================🦀 100% 106 KiB/s Time: 00:00:03 +[ML] Loaded! Executing the payload now + +[ 3.572716] mingo version 0.19.0 +[ 3.572924] Booting on: Raspberry Pi 3 +[ 3.573379] MMU online: +[ 3.573672] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 3.575416] Virtual Physical Size Attr Entity +[ 3.577160] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 3.578905] 0xffff_ffff_c000_0000..0xffff_ffff_c001_ffff --> 0x00_0008_0000..0x00_0009_ffff | 128 KiB | C RO X | Kernel code and RO data +[ 3.580519] 0xffff_ffff_c002_0000..0xffff_ffff_c009_ffff --> 0x00_000a_0000..0x00_0011_ffff | 512 KiB | C RW XN | Kernel data and bss +[ 3.582089] 0xffff_ffff_c00a_0000..0xffff_ffff_c109_ffff --> 0x00_0012_0000..0x00_0111_ffff | 16 MiB | C RW XN | Kernel heap +[ 3.583573] 0xffff_ffff_c10a_0000..0xffff_ffff_c10a_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART +[ 3.585090] | BCM GPIO +[ 3.586542] 0xffff_ffff_c10b_0000..0xffff_ffff_c10b_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Interrupt Controller +[ 3.588167] 0xffff_ffff_c18b_0000..0xffff_ffff_c192_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack +[ 3.589770] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 3.591515] Current privilege level: EL1 + +[...] + +[ 3.597624] Kernel heap: +[ 3.597928] Used: 2512 Byte (3 KiB) +[ 3.598415] Free: 16774704 Byte (16 MiB) +[ 3.598957] Echoing input now +``` + +## Diff to previous +```diff + +diff -uNr 18_backtrace/kernel/Cargo.toml 19_kernel_heap/kernel/Cargo.toml +--- 18_backtrace/kernel/Cargo.toml ++++ 19_kernel_heap/kernel/Cargo.toml +@@ -1,11 +1,12 @@ + [package] + name = "mingo" +-version = "0.18.0" ++version = "0.19.0" + authors = ["Andre Richter "] + edition = "2021" + + [features] + default = [] ++debug_prints = [] + bsp_rpi3 = ["tock-registers"] + bsp_rpi4 = ["tock-registers"] + test_build = ["qemu-exit"] +@@ -17,6 +18,7 @@ + [dependencies] + test-types = { path = "../libraries/test-types" } + debug-symbol-types = { path = "../libraries/debug-symbol-types" } ++linked_list_allocator = { version = "0.10.x", default-features = false, features = ["const_mut_refs"] } + + # Optional dependencies + tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + +diff -uNr 18_backtrace/kernel/src/bsp/device_driver/arm/gicv2.rs 19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2.rs +--- 18_backtrace/kernel/src/bsp/device_driver/arm/gicv2.rs ++++ 19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2.rs +@@ -86,13 +86,13 @@ + synchronization, + synchronization::InitStateLock, + }; ++use alloc::vec::Vec; + + //-------------------------------------------------------------------------------------------------- + // Private Definitions + //-------------------------------------------------------------------------------------------------- + +-type HandlerTable = [Option>; +- IRQNumber::MAX_INCLUSIVE + 1]; ++type HandlerTable = Vec>>; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions +@@ -118,7 +118,7 @@ + //-------------------------------------------------------------------------------------------------- + + impl GICv2 { +- const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. ++ const MAX_IRQ_NUMBER: usize = 1019; + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + +@@ -134,7 +134,7 @@ + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), +- handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), ++ handler_table: InitStateLock::new(Vec::new()), + } + } + } +@@ -152,6 +152,9 @@ + } + + unsafe fn init(&self) -> Result<(), &'static str> { ++ self.handler_table ++ .write(|table| table.resize(IRQNumber::MAX_INCLUSIVE + 1, None)); ++ + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + +diff -uNr 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +--- 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ++++ 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +@@ -16,6 +16,7 @@ + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, + }; ++use alloc::vec::Vec; + use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, +@@ -52,8 +53,7 @@ + /// Abstraction for the ReadOnly parts of the associated MMIO registers. + type ReadOnlyRegisters = MMIODerefWrapper; + +-type HandlerTable = [Option>; +- PeripheralIRQ::MAX_INCLUSIVE + 1]; ++type HandlerTable = Vec>>; + + //-------------------------------------------------------------------------------------------------- + // Public Definitions +@@ -85,10 +85,16 @@ + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), +- handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), ++ handler_table: InitStateLock::new(Vec::new()), + } + } + ++ /// Called by the kernel to bring up the device. ++ pub fn init(&self) { ++ self.handler_table ++ .write(|table| table.resize(PeripheralIRQ::MAX_INCLUSIVE + 1, None)); ++ } ++ + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + +diff -uNr 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +--- 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ++++ 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +@@ -109,6 +109,12 @@ + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } ++ ++ unsafe fn init(&self) -> Result<(), &'static str> { ++ self.periph.init(); ++ ++ Ok(()) ++ } + } + + impl exception::asynchronous::interface::IRQManager for InterruptController { + +diff -uNr 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +--- 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ++++ 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +@@ -327,6 +327,13 @@ + self.chars_written += 1; + } + ++ /// Send a slice of characters. ++ fn write_array(&mut self, a: &[char]) { ++ for c in a { ++ self.write_char(*c); ++ } ++ } ++ + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. +@@ -443,6 +450,10 @@ + self.inner.lock(|inner| inner.write_char(c)); + } + ++ fn write_array(&self, a: &[char]) { ++ self.inner.lock(|inner| inner.write_array(a)); ++ } ++ + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + +diff -uNr 18_backtrace/kernel/src/bsp/raspberrypi/kernel.ld 19_kernel_heap/kernel/src/bsp/raspberrypi/kernel.ld +--- 18_backtrace/kernel/src/bsp/raspberrypi/kernel.ld ++++ 19_kernel_heap/kernel/src/bsp/raspberrypi/kernel.ld +@@ -35,6 +35,7 @@ + { + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); ++ segment_heap PT_LOAD FLAGS(6); + segment_boot_core_stack PT_LOAD FLAGS(6); + } + +@@ -84,6 +85,18 @@ + __data_end_exclusive = .; + + /*********************************************************************************************** ++ * Heap ++ ***********************************************************************************************/ ++ __heap_start = .; ++ .heap (NOLOAD) : ++ { ++ . += 16 * 1024 * 1024; ++ } :segment_heap ++ __heap_end_exclusive = .; ++ ++ ASSERT((. & PAGE_MASK) == 0, "Heap is not page aligned") ++ ++ /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + +diff -uNr 18_backtrace/kernel/src/bsp/raspberrypi/memory/mmu.rs 19_kernel_heap/kernel/src/bsp/raspberrypi/memory/mmu.rs +--- 18_backtrace/kernel/src/bsp/raspberrypi/memory/mmu.rs ++++ 19_kernel_heap/kernel/src/bsp/raspberrypi/memory/mmu.rs +@@ -122,6 +122,16 @@ + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) + } + ++/// The heap pages. ++pub fn virt_heap_region() -> MemoryRegion { ++ let num_pages = size_to_num_pages(super::heap_size()); ++ ++ let start_page_addr = super::virt_heap_start(); ++ let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); ++ ++ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) ++} ++ + /// The boot core stack pages. + pub fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); +@@ -169,6 +179,14 @@ + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); + ++ let virt_heap_region = virt_heap_region(); ++ generic_mmu::kernel_add_mapping_record( ++ "Kernel heap", ++ &virt_heap_region, ++ &kernel_virt_to_phys_region(virt_heap_region), ++ &kernel_page_attributes(virt_heap_region.start_page_addr()), ++ ); ++ + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", + +diff -uNr 18_backtrace/kernel/src/bsp/raspberrypi/memory.rs 19_kernel_heap/kernel/src/bsp/raspberrypi/memory.rs +--- 18_backtrace/kernel/src/bsp/raspberrypi/memory.rs ++++ 19_kernel_heap/kernel/src/bsp/raspberrypi/memory.rs +@@ -28,7 +28,11 @@ + //! | .bss | + //! | | + //! +---------------------------------------+ +-//! | | data_end_exclusive ++//! | | heap_start == data_end_exclusive ++//! | .heap | ++//! | | ++//! +---------------------------------------+ ++//! | | heap_end_exclusive + //! | | + //! + //! +@@ -50,7 +54,11 @@ + //! | .bss | + //! | | + //! +---------------------------------------+ +-//! | | mmio_remap_start == data_end_exclusive ++//! | | heap_start == data_end_exclusive ++//! | .heap | ++//! | | ++//! +---------------------------------------+ ++//! | | mmio_remap_start == heap_end_exclusive + //! | VA region for MMIO remapping | + //! | | + //! +---------------------------------------+ +@@ -83,6 +91,9 @@ + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + ++ static __heap_start: UnsafeCell<()>; ++ static __heap_end_exclusive: UnsafeCell<()>; ++ + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + +@@ -179,6 +190,22 @@ + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } + } + ++/// Start page address of the heap segment. ++#[inline(always)] ++fn virt_heap_start() -> PageAddress { ++ PageAddress::from(unsafe { __heap_start.get() as usize }) ++} ++ ++/// Size of the heap segment. ++/// ++/// # Safety ++/// ++/// - Value is provided by the linker script and must be trusted as-is. ++#[inline(always)] ++fn heap_size() -> usize { ++ unsafe { (__heap_end_exclusive.get() as usize) - (__heap_start.get() as usize) } ++} ++ + /// Start page address of the MMIO remap reservation. + /// + /// # Safety + +diff -uNr 18_backtrace/kernel/src/console/buffer_console.rs 19_kernel_heap/kernel/src/console/buffer_console.rs +--- 18_backtrace/kernel/src/console/buffer_console.rs ++++ 19_kernel_heap/kernel/src/console/buffer_console.rs +@@ -0,0 +1,108 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! A console that buffers input during the init phase. ++ ++use super::interface; ++use crate::{console, info, synchronization, synchronization::InitStateLock}; ++use core::fmt; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++const BUF_SIZE: usize = 1024 * 64; ++ ++pub struct BufferConsoleInner { ++ buf: [char; BUF_SIZE], ++ write_ptr: usize, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++pub struct BufferConsole { ++ inner: InitStateLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++pub static BUFFER_CONSOLE: BufferConsole = BufferConsole { ++ inner: InitStateLock::new(BufferConsoleInner { ++ // Use the null character, so this lands in .bss and does not waste space in the binary. ++ buf: ['\0'; BUF_SIZE], ++ write_ptr: 0, ++ }), ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl BufferConsoleInner { ++ fn write_char(&mut self, c: char) { ++ if self.write_ptr < (BUF_SIZE - 1) { ++ self.buf[self.write_ptr] = c; ++ self.write_ptr += 1; ++ } ++ } ++} ++ ++impl fmt::Write for BufferConsoleInner { ++ fn write_str(&mut self, s: &str) -> fmt::Result { ++ for c in s.chars() { ++ self.write_char(c); ++ } ++ ++ Ok(()) ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++use synchronization::interface::ReadWriteEx; ++ ++impl BufferConsole { ++ /// Dump the buffer. ++ /// ++ /// # Invariant ++ /// ++ /// It is expected that this is only called when self != crate::console::console(). ++ pub fn dump(&self) { ++ self.inner.read(|inner| { ++ console::console().write_array(&inner.buf[0..inner.write_ptr]); ++ ++ if inner.write_ptr == (BUF_SIZE - 1) { ++ info!("Pre-UART buffer overflowed"); ++ } else if inner.write_ptr > 0 { ++ info!("End of pre-UART buffer") ++ } ++ }); ++ } ++} ++ ++impl interface::Write for BufferConsole { ++ fn write_char(&self, c: char) { ++ self.inner.write(|inner| inner.write_char(c)); ++ } ++ ++ fn write_array(&self, _a: &[char]) {} ++ ++ fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result { ++ self.inner.write(|inner| fmt::Write::write_fmt(inner, args)) ++ } ++ ++ fn flush(&self) {} ++} ++ ++impl interface::Read for BufferConsole { ++ fn clear_rx(&self) {} ++} ++ ++impl interface::Statistics for BufferConsole {} ++impl interface::All for BufferConsole {} + +diff -uNr 18_backtrace/kernel/src/console/null_console.rs 19_kernel_heap/kernel/src/console/null_console.rs +--- 18_backtrace/kernel/src/console/null_console.rs ++++ 19_kernel_heap/kernel/src/console/null_console.rs +@@ -1,41 +0,0 @@ +-// SPDX-License-Identifier: MIT OR Apache-2.0 +-// +-// Copyright (c) 2022-2023 Andre Richter +- +-//! Null console. +- +-use super::interface; +-use core::fmt; +- +-//-------------------------------------------------------------------------------------------------- +-// Public Definitions +-//-------------------------------------------------------------------------------------------------- +- +-pub struct NullConsole; +- +-//-------------------------------------------------------------------------------------------------- +-// Global instances +-//-------------------------------------------------------------------------------------------------- +- +-pub static NULL_CONSOLE: NullConsole = NullConsole {}; +- +-//-------------------------------------------------------------------------------------------------- +-// Public Code +-//-------------------------------------------------------------------------------------------------- +- +-impl interface::Write for NullConsole { +- fn write_char(&self, _c: char) {} +- +- fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { +- fmt::Result::Ok(()) +- } +- +- fn flush(&self) {} +-} +- +-impl interface::Read for NullConsole { +- fn clear_rx(&self) {} +-} +- +-impl interface::Statistics for NullConsole {} +-impl interface::All for NullConsole {} + +diff -uNr 18_backtrace/kernel/src/console.rs 19_kernel_heap/kernel/src/console.rs +--- 18_backtrace/kernel/src/console.rs ++++ 19_kernel_heap/kernel/src/console.rs +@@ -4,7 +4,7 @@ + + //! System console. + +-mod null_console; ++mod buffer_console; + + use crate::synchronization; + +@@ -21,6 +21,9 @@ + /// Write a single character. + fn write_char(&self, c: char); + ++ /// Write a slice of characters. ++ fn write_array(&self, a: &[char]); ++ + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + +@@ -61,7 +64,7 @@ + //-------------------------------------------------------------------------------------------------- + + static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = +- InitStateLock::new(&null_console::NULL_CONSOLE); ++ InitStateLock::new(&buffer_console::BUFFER_CONSOLE); + + //-------------------------------------------------------------------------------------------------- + // Public Code +@@ -71,6 +74,15 @@ + /// Register a new console. + pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); ++ ++ static FIRST_SWITCH: InitStateLock = InitStateLock::new(true); ++ FIRST_SWITCH.write(|first| { ++ if *first { ++ *first = false; ++ ++ buffer_console::BUFFER_CONSOLE.dump(); ++ } ++ }); + } + + /// Return a reference to the currently registered console. + +diff -uNr 18_backtrace/kernel/src/driver.rs 19_kernel_heap/kernel/src/driver.rs +--- 18_backtrace/kernel/src/driver.rs ++++ 19_kernel_heap/kernel/src/driver.rs +@@ -8,23 +8,10 @@ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, + }; ++use alloc::vec::Vec; + use core::fmt; + + //-------------------------------------------------------------------------------------------------- +-// Private Definitions +-//-------------------------------------------------------------------------------------------------- +- +-const NUM_DRIVERS: usize = 5; +- +-struct DriverManagerInner +-where +- T: 'static, +-{ +- next_index: usize, +- descriptors: [Option>; NUM_DRIVERS], +-} +- +-//-------------------------------------------------------------------------------------------------- + // Public Definitions + //-------------------------------------------------------------------------------------------------- + +@@ -68,7 +55,6 @@ + pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + + /// A descriptor for device drivers. +-#[derive(Copy, Clone)] + pub struct DeviceDriverDescriptor + where + T: 'static, +@@ -83,7 +69,7 @@ + where + T: 'static, + { +- inner: InitStateLock>, ++ descriptors: InitStateLock>>, + } + + //-------------------------------------------------------------------------------------------------- +@@ -93,23 +79,6 @@ + static DRIVER_MANAGER: DriverManager = DriverManager::new(); + + //-------------------------------------------------------------------------------------------------- +-// Private Code +-//-------------------------------------------------------------------------------------------------- +- +-impl DriverManagerInner +-where +- T: 'static + Copy, +-{ +- /// Create an instance. +- pub const fn new() -> Self { +- Self { +- next_index: 0, +- descriptors: [None; NUM_DRIVERS], +- } +- } +-} +- +-//-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- + +@@ -135,32 +104,19 @@ + + impl DriverManager + where +- T: fmt::Display + Copy, ++ T: fmt::Display, + { + /// Create an instance. + pub const fn new() -> Self { + Self { +- inner: InitStateLock::new(DriverManagerInner::new()), ++ descriptors: InitStateLock::new(Vec::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { +- self.inner.write(|inner| { +- inner.descriptors[inner.next_index] = Some(descriptor); +- inner.next_index += 1; +- }) +- } +- +- /// Helper for iterating over registered drivers. +- fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { +- self.inner.read(|inner| { +- inner +- .descriptors +- .iter() +- .filter_map(|x| x.as_ref()) +- .for_each(f) +- }) ++ self.descriptors ++ .write(|descriptors| descriptors.push(descriptor)); + } + + /// Fully initialize all drivers and their interrupts handlers. +@@ -169,53 +125,54 @@ + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { +- self.for_each_descriptor(|descriptor| { +- // 1. Initialize driver. +- if let Err(x) = descriptor.device_driver.init() { +- panic!( +- "Error initializing driver: {}: {}", +- descriptor.device_driver.compatible(), +- x +- ); +- } +- +- // 2. Call corresponding post init callback. +- if let Some(callback) = &descriptor.post_init_callback { +- if let Err(x) = callback() { ++ self.descriptors.read(|descriptors| { ++ for descriptor in descriptors { ++ // 1. Initialize driver. ++ if let Err(x) = descriptor.device_driver.init() { + panic!( +- "Error during driver post-init callback: {}: {}", ++ "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } ++ ++ // 2. Call corresponding post init callback. ++ if let Some(callback) = &descriptor.post_init_callback { ++ if let Err(x) = callback() { ++ panic!( ++ "Error during driver post-init callback: {}: {}", ++ descriptor.device_driver.compatible(), ++ x ++ ); ++ } ++ } + } +- }); + +- // 3. After all post-init callbacks were done, the interrupt controller should be +- // registered and functional. So let drivers register with it now. +- self.for_each_descriptor(|descriptor| { +- if let Some(irq_number) = &descriptor.irq_number { +- if let Err(x) = descriptor +- .device_driver +- .register_and_enable_irq_handler(irq_number) +- { +- panic!( +- "Error during driver interrupt handler registration: {}: {}", +- descriptor.device_driver.compatible(), +- x +- ); ++ // 3. After all post-init callbacks were done, the interrupt controller should be ++ // registered and functional. So let drivers register with it now. ++ for descriptor in descriptors { ++ if let Some(irq_number) = &descriptor.irq_number { ++ if let Err(x) = descriptor ++ .device_driver ++ .register_and_enable_irq_handler(irq_number) ++ { ++ panic!( ++ "Error during driver interrupt handler registration: {}: {}", ++ descriptor.device_driver.compatible(), ++ x ++ ); ++ } + } + } +- }); ++ }) + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { +- let mut i: usize = 1; +- self.for_each_descriptor(|descriptor| { +- info!(" {}. {}", i, descriptor.device_driver.compatible()); +- +- i += 1; ++ self.descriptors.read(|descriptors| { ++ for (i, desc) in descriptors.iter().enumerate() { ++ info!(" {}. {}", i + 1, desc.device_driver.compatible()); ++ } + }); + } + } + +diff -uNr 18_backtrace/kernel/src/lib.rs 19_kernel_heap/kernel/src/lib.rs +--- 18_backtrace/kernel/src/lib.rs ++++ 19_kernel_heap/kernel/src/lib.rs +@@ -110,6 +110,7 @@ + + #![allow(clippy::upper_case_acronyms)] + #![allow(incomplete_features)] ++#![feature(alloc_error_handler)] + #![feature(asm_const)] + #![feature(const_option)] + #![feature(core_intrinsics)] +@@ -130,6 +131,8 @@ + #![reexport_test_harness_main = "test_main"] + #![test_runner(crate::test_runner)] + ++extern crate alloc; ++ + mod panic_wait; + mod synchronization; + + +diff -uNr 18_backtrace/kernel/src/main.rs 19_kernel_heap/kernel/src/main.rs +--- 18_backtrace/kernel/src/main.rs ++++ 19_kernel_heap/kernel/src/main.rs +@@ -13,6 +13,8 @@ + #![no_main] + #![no_std] + ++extern crate alloc; ++ + use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + + /// Early init code. +@@ -73,6 +75,9 @@ + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + ++ info!("Kernel heap:"); ++ memory::heap_alloc::kernel_heap_allocator().print_usage(); ++ + info!("Echoing input now"); + cpu::wait_forever(); + } + +diff -uNr 18_backtrace/kernel/src/memory/heap_alloc.rs 19_kernel_heap/kernel/src/memory/heap_alloc.rs +--- 18_backtrace/kernel/src/memory/heap_alloc.rs ++++ 19_kernel_heap/kernel/src/memory/heap_alloc.rs +@@ -0,0 +1,147 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Heap allocation. ++ ++use crate::{ ++ backtrace, bsp, common, debug, info, ++ memory::{Address, Virtual}, ++ synchronization, ++ synchronization::IRQSafeNullLock, ++ warn, ++}; ++use alloc::alloc::{GlobalAlloc, Layout}; ++use core::sync::atomic::{AtomicBool, Ordering}; ++use linked_list_allocator::Heap as LinkedListHeap; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// A heap allocator that can be lazyily initialized. ++pub struct HeapAllocator { ++ inner: IRQSafeNullLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Global instances ++//-------------------------------------------------------------------------------------------------- ++ ++#[global_allocator] ++static KERNEL_HEAP_ALLOCATOR: HeapAllocator = HeapAllocator::new(); ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++#[inline(always)] ++fn debug_print_alloc_dealloc(operation: &'static str, ptr: *mut u8, layout: Layout) { ++ let size = layout.size(); ++ let (size_h, size_unit) = common::size_human_readable_ceil(size); ++ let addr = Address::::new(ptr as usize); ++ ++ debug!( ++ "Kernel Heap: {}\n \ ++ Size: {:#x} ({} {})\n \ ++ Start: {}\n \ ++ End excl: {}\n\n \ ++ {}", ++ operation, ++ size, ++ size_h, ++ size_unit, ++ addr, ++ addr + size, ++ backtrace::Backtrace ++ ); ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++use synchronization::interface::Mutex; ++ ++#[alloc_error_handler] ++fn alloc_error_handler(layout: Layout) -> ! { ++ panic!("Allocation error: {:?}", layout) ++} ++ ++/// Return a reference to the kernel's heap allocator. ++pub fn kernel_heap_allocator() -> &'static HeapAllocator { ++ &KERNEL_HEAP_ALLOCATOR ++} ++ ++impl HeapAllocator { ++ /// Create an instance. ++ pub const fn new() -> Self { ++ Self { ++ inner: IRQSafeNullLock::new(LinkedListHeap::empty()), ++ } ++ } ++ ++ /// Print the current heap usage. ++ pub fn print_usage(&self) { ++ let (used, free) = KERNEL_HEAP_ALLOCATOR ++ .inner ++ .lock(|inner| (inner.used(), inner.free())); ++ ++ if used >= 1024 { ++ let (used_h, used_unit) = common::size_human_readable_ceil(used); ++ info!(" Used: {} Byte ({} {})", used, used_h, used_unit); ++ } else { ++ info!(" Used: {} Byte", used); ++ } ++ ++ if free >= 1024 { ++ let (free_h, free_unit) = common::size_human_readable_ceil(free); ++ info!(" Free: {} Byte ({} {})", free, free_h, free_unit); ++ } else { ++ info!(" Free: {} Byte", free); ++ } ++ } ++} ++ ++unsafe impl GlobalAlloc for HeapAllocator { ++ unsafe fn alloc(&self, layout: Layout) -> *mut u8 { ++ let result = KERNEL_HEAP_ALLOCATOR ++ .inner ++ .lock(|inner| inner.allocate_first_fit(layout).ok()); ++ ++ match result { ++ None => core::ptr::null_mut(), ++ Some(allocation) => { ++ let ptr = allocation.as_ptr(); ++ ++ debug_print_alloc_dealloc("Allocation", ptr, layout); ++ ++ ptr ++ } ++ } ++ } ++ ++ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { ++ KERNEL_HEAP_ALLOCATOR ++ .inner ++ .lock(|inner| inner.deallocate(core::ptr::NonNull::new_unchecked(ptr), layout)); ++ ++ debug_print_alloc_dealloc("Free", ptr, layout); ++ } ++} ++ ++/// Query the BSP for the heap region and initialize the kernel's heap allocator with it. ++pub fn kernel_init_heap_allocator() { ++ static INIT_DONE: AtomicBool = AtomicBool::new(false); ++ if INIT_DONE.load(Ordering::Relaxed) { ++ warn!("Already initialized"); ++ return; ++ } ++ ++ let region = bsp::memory::mmu::virt_heap_region(); ++ ++ KERNEL_HEAP_ALLOCATOR.inner.lock(|inner| unsafe { ++ inner.init(region.start_addr().as_usize() as *mut u8, region.size()) ++ }); ++ ++ INIT_DONE.store(true, Ordering::Relaxed); ++} + +diff -uNr 18_backtrace/kernel/src/memory/mmu/mapping_record.rs 19_kernel_heap/kernel/src/memory/mmu/mapping_record.rs +--- 18_backtrace/kernel/src/memory/mmu/mapping_record.rs ++++ 19_kernel_heap/kernel/src/memory/mmu/mapping_record.rs +@@ -8,7 +8,8 @@ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, + }; +-use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; ++use crate::{bsp, common, info, synchronization, synchronization::InitStateLock}; ++use alloc::{vec, vec::Vec}; + + //-------------------------------------------------------------------------------------------------- + // Private Definitions +@@ -16,9 +17,8 @@ + + /// Type describing a virtual memory mapping. + #[allow(missing_docs)] +-#[derive(Copy, Clone)] + struct MappingRecordEntry { +- pub users: [Option<&'static str>; 5], ++ pub users: Vec<&'static str>, + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, +@@ -26,7 +26,7 @@ + } + + struct MappingRecord { +- inner: [Option; 12], ++ inner: Vec, + } + + //-------------------------------------------------------------------------------------------------- +@@ -48,7 +48,7 @@ + attr: &AttributeFields, + ) -> Self { + Self { +- users: [Some(name), None, None, None, None], ++ users: vec![name], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), +@@ -56,54 +56,28 @@ + } + } + +- fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { +- if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { +- return Ok(x); +- }; +- +- Err("Storage for user info exhausted") +- } +- +- pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { +- let x = self.find_next_free_user()?; +- *x = Some(user); +- Ok(()) ++ pub fn add_user(&mut self, user: &'static str) { ++ self.users.push(user); + } + } + + impl MappingRecord { + pub const fn new() -> Self { +- Self { inner: [None; 12] } +- } +- +- fn size(&self) -> usize { +- self.inner.iter().filter(|x| x.is_some()).count() ++ Self { inner: Vec::new() } + } + + fn sort(&mut self) { +- let upper_bound_exclusive = self.size(); +- let entries = &mut self.inner[0..upper_bound_exclusive]; +- +- if !entries.is_sorted_by_key(|item| item.unwrap().virt_start_addr) { +- entries.sort_unstable_by_key(|item| item.unwrap().virt_start_addr) ++ if !self.inner.is_sorted_by_key(|item| item.virt_start_addr) { ++ self.inner.sort_unstable_by_key(|item| item.virt_start_addr) + } + } + +- fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { +- if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { +- return Ok(x); +- } +- +- Err("Storage for mapping info exhausted") +- } +- + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() +- .filter_map(|x| x.as_mut()) + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { +@@ -124,10 +98,8 @@ + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +- ) -> Result<(), &'static str> { +- let x = self.find_next_free()?; +- +- *x = Some(MappingRecordEntry::new( ++ ) { ++ self.inner.push(MappingRecordEntry::new( + name, + virt_region, + phys_region, +@@ -135,8 +107,6 @@ + )); + + self.sort(); +- +- Ok(()) + } + + pub fn print(&self) { +@@ -147,7 +117,7 @@ + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + +- for i in self.inner.iter().flatten() { ++ for i in self.inner.iter() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); +@@ -183,16 +153,14 @@ + attr, + acc_p, + xn, +- i.users[0].unwrap() ++ i.users[0] + ); + +- for k in i.users[1..].iter() { +- if let Some(additional_user) = *k { +- info!( ++ for k in &i.users[1..] { ++ info!( + " | {}", +- additional_user ++ k + ); +- } + } + } + +@@ -211,7 +179,7 @@ + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +-) -> Result<(), &'static str> { ++) { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) + } + +@@ -224,9 +192,7 @@ + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + +- if let Err(x) = dup.add_user(new_user) { +- warn!("{}", x); +- } ++ dup.add_user(new_user); + + Some(dup.virt_start_addr) + }) + +diff -uNr 18_backtrace/kernel/src/memory/mmu.rs 19_kernel_heap/kernel/src/memory/mmu.rs +--- 18_backtrace/kernel/src/memory/mmu.rs ++++ 19_kernel_heap/kernel/src/memory/mmu.rs +@@ -17,7 +17,6 @@ + bsp, + memory::{Address, Physical, Virtual}, + synchronization::{self, interface::Mutex}, +- warn, + }; + use core::{fmt, num::NonZeroUsize}; + +@@ -176,9 +175,7 @@ + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) { +- if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { +- warn!("{}", x); +- } ++ mapping_record::kernel_add(name, virt_region, phys_region, attr); + } + + /// MMIO remapping in the kernel translation tables. + +diff -uNr 18_backtrace/kernel/src/memory.rs 19_kernel_heap/kernel/src/memory.rs +--- 18_backtrace/kernel/src/memory.rs ++++ 19_kernel_heap/kernel/src/memory.rs +@@ -4,6 +4,7 @@ + + //! Memory Management. + ++pub mod heap_alloc; + pub mod mmu; + + use crate::{bsp, common}; +@@ -163,6 +164,7 @@ + /// Initialize the memory subsystem. + pub fn init() { + mmu::kernel_init_mmio_va_allocator(); ++ heap_alloc::kernel_init_heap_allocator(); + } + + //-------------------------------------------------------------------------------------------------- + +diff -uNr 18_backtrace/kernel/src/print.rs 19_kernel_heap/kernel/src/print.rs +--- 18_backtrace/kernel/src/print.rs ++++ 19_kernel_heap/kernel/src/print.rs +@@ -82,3 +82,31 @@ + )); + }) + } ++ ++/// Debug print, with a newline. ++#[macro_export] ++macro_rules! debug { ++ ($string:expr) => ({ ++ if cfg!(feature = "debug_prints") { ++ let timestamp = $crate::time::time_manager().uptime(); ++ ++ $crate::print::_print(format_args_nl!( ++ concat!("<[>D {:>3}.{:06}> ", $string), ++ timestamp.as_secs(), ++ timestamp.subsec_micros(), ++ )); ++ } ++ }); ++ ($format_string:expr, $($arg:tt)*) => ({ ++ if cfg!(feature = "debug_prints") { ++ let timestamp = $crate::time::time_manager().uptime(); ++ ++ $crate::print::_print(format_args_nl!( ++ concat!("3}.{:06}> ", $format_string), ++ timestamp.as_secs(), ++ timestamp.subsec_micros(), ++ $($arg)* ++ )); ++ } ++ }) ++} + +diff -uNr 18_backtrace/kernel/src/state.rs 19_kernel_heap/kernel/src/state.rs +--- 18_backtrace/kernel/src/state.rs ++++ 19_kernel_heap/kernel/src/state.rs +@@ -52,7 +52,7 @@ + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + +- /// Create an instance. ++ /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + +diff -uNr 18_backtrace/Makefile 19_kernel_heap/Makefile +--- 18_backtrace/Makefile ++++ 19_kernel_heap/Makefile +@@ -16,6 +16,11 @@ + # Default to a serial device name that is common in Linux. + DEV_SERIAL ?= /dev/ttyUSB0 + ++# Optional debug prints. ++ifdef DEBUG_PRINTS ++ FEATURES = --features debug_prints ++endif ++ + # Optional integration test name. + ifdef TEST + TEST_ARG = --test $(TEST) +@@ -70,7 +75,7 @@ + ##-------------------------------------------------------------------------------------------------- + KERNEL_MANIFEST = kernel/Cargo.toml + KERNEL_LINKER_SCRIPT = kernel.ld +-LAST_BUILD_CONFIG = target/$(BSP).build_config ++LAST_BUILD_CONFIG = target/$(BSP)_$(DEBUG_PRINTS).build_config + + KERNEL_ELF_RAW = target/$(TARGET)/release/kernel + # This parses cargo's dep-info file. +@@ -117,17 +122,17 @@ + -D warnings \ + -D missing_docs + +-FEATURES = --features bsp_$(BSP) ++FEATURES += --features bsp_$(BSP) + COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + + # build-std can be skipped for helper commands that do not rely on correct stack frames and other + # custom compiler options. This results in a huge speedup. +-RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -Z build-std=core --manifest-path $(KERNEL_MANIFEST) ++RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -Z build-std=core,alloc --manifest-path $(KERNEL_MANIFEST) + DOC_CMD = cargo doc $(COMPILER_ARGS) + CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +-TEST_CMD = cargo test $(COMPILER_ARGS) -Z build-std=core --manifest-path $(KERNEL_MANIFEST) ++TEST_CMD = cargo test $(COMPILER_ARGS) -Z build-std=core,alloc --manifest-path $(KERNEL_MANIFEST) + OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +``` diff --git a/19_kernel_heap/kernel/Cargo.toml b/19_kernel_heap/kernel/Cargo.toml new file mode 100644 index 000000000..03ebfc020 --- /dev/null +++ b/19_kernel_heap/kernel/Cargo.toml @@ -0,0 +1,72 @@ +[package] +name = "mingo" +version = "0.19.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +debug_prints = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } +debug-symbol-types = { path = "../libraries/debug-symbol-types" } +linked_list_allocator = { version = "0.10.x", default-features = false, features = ["const_mut_refs"] } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##-------------------------------------------------------------------------------------------------- +## Testing +##-------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false + +[[test]] +name = "05_backtrace_sanity" +harness = false + +[[test]] +name = "06_backtrace_invalid_frame" +harness = false + +[[test]] +name = "07_backtrace_invalid_link" +harness = false diff --git a/19_kernel_heap/kernel/build.rs b/19_kernel_heap/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/19_kernel_heap/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/backtrace.rs b/19_kernel_heap/kernel/src/_arch/aarch64/backtrace.rs new file mode 100644 index 000000000..c2fb8dcb4 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/backtrace.rs @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Architectural backtracing support. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::backtrace::arch_backtrace + +use crate::{ + backtrace::BacktraceItem, + memory::{Address, Virtual}, +}; +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// A Stack frame record. +/// +/// # Note +/// +/// The convention is that `previous_record` is valid as long as it contains a non-null value. +/// Therefore, it is possible to type the member as `Option<&StackFrameRecord>` because of Rust's +/// `null-pointer optimization`. +#[repr(C)] +struct StackFrameRecord<'a> { + previous_record: Option<&'a StackFrameRecord<'a>>, + link: Address, +} + +struct StackFrameRecordIterator<'a> { + cur: &'a StackFrameRecord<'a>, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl<'a> Iterator for StackFrameRecordIterator<'a> { + type Item = BacktraceItem; + + fn next(&mut self) -> Option { + static ABORT_FRAME: StackFrameRecord = StackFrameRecord { + previous_record: None, + link: Address::new(0), + }; + + // If previous is None, this is the root frame, so iteration will stop here. + let previous = self.cur.previous_record?; + + // Need to abort if the pointer to the previous frame record is invalid. + let prev_addr = Address::::new(previous as *const _ as usize); + if !prev_addr.is_valid_stack_addr() { + // This allows to return the error and then stop on the next iteration. + self.cur = &ABORT_FRAME; + return Some(BacktraceItem::InvalidFramePointer(prev_addr)); + } + + let ret = if !self.cur.link.is_valid_code_addr() { + Some(BacktraceItem::InvalidLink(self.cur.link)) + } else { + // The link points to the instruction to be executed _after_ returning from a branch. + // However, we want to show the instruction that caused the branch, so subtract by one + // instruction. + // + // This might be called from panic!, so it must not panic itself on the subtraction. + let link = if self.cur.link >= Address::new(4) { + self.cur.link - 4 + } else { + self.cur.link + }; + + Some(BacktraceItem::Link(link)) + }; + + // Advance the iterator. + self.cur = previous; + + ret + } +} + +fn stack_frame_record_iterator<'a>() -> Option> { + let fp = Address::::new(FP.get() as usize); + if !fp.is_valid_stack_addr() { + return None; + } + + Some(StackFrameRecordIterator { + cur: unsafe { &*(fp.as_usize() as *const _) }, + }) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Architectural implementation of the backtrace. +pub fn backtrace(f: impl FnOnce(Option<&mut dyn Iterator>)) { + f(stack_frame_record_iterator().as_mut().map(|s| s as _)) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(feature = "test_build")] +#[inline(always)] +/// Hack for corrupting the previous frame address in the current stack frame. +/// +/// # Safety +/// +/// - To be used only by testing code. +pub unsafe fn corrupt_previous_frame_addr() { + let sf = FP.get() as *mut usize; + *sf = 0x123; +} + +#[cfg(feature = "test_build")] +#[inline(always)] +/// Hack for corrupting the link in the current stack frame. +/// +/// # Safety +/// +/// - To be used only by testing code. +pub unsafe fn corrupt_link() { + let sf = FP.get() as *mut StackFrameRecord; + (*sf).link = Address::new(0x456); +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/cpu.rs b/19_kernel_heap/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/cpu/boot.rs b/19_kernel_heap/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..b8033fbe8 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use crate::{memory, memory::Address}; +use aarch64_cpu::{asm, registers::*}; +use core::{ + arch::global_asm, + sync::atomic::{compiler_fence, Ordering}, +}; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(virt_kernel_init_addr); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(virt_boot_core_stack_end_exclusive_addr); +} + +/// Reset the backtrace by setting link register and frame pointer to zero. +/// +/// # Safety +/// +/// - This function must only be used immediately before entering EL1. +#[inline(always)] +unsafe fn prepare_backtrace_reset() { + compiler_fence(Ordering::SeqCst); + FP.set(0); + LR.set(0); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) -> ! { + prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr, + virt_kernel_init_addr, + ); + + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + + // Make the function we return to the root of a backtrace. + prepare_backtrace_reset(); + + // Use `eret` to "return" to EL1. Since virtual memory will already be enabled, this results in + // execution of kernel_init() in EL1 from its _virtual address_. + asm::eret() +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/cpu/boot.s b/19_kernel_heap/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..1a8c88010 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +// Load the address of a symbol into a register, absolute. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_ABS register, symbol + movz \register, #:abs_g3:\symbol + movk \register, #:abs_g2_nc:\symbol + movk \register, #:abs_g1_nc:\symbol + movk \register, #:abs_g0_nc:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Load the base address of the kernel's translation tables. + ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + + // Load the _absolute_ addresses of the following symbols. Since the kernel is linked at + // the top of the 64 bit address space, these are effectively virtual addresses. + ADR_ABS x1, __boot_core_stack_end_exclusive + ADR_ABS x2, kernel_init + + // Load the PC-relative address of the stack and set the stack pointer. + // + // Since _start() is the first function that runs after the firmware has loaded the kernel + // into memory, retrieving this symbol PC-relative returns the "physical" address. + // + // Setting the stack pointer to this value ensures that anything that still runs in EL2, + // until the kernel returns to EL1 with the MMU enabled, works as well. After the return to + // EL1, the virtual address of the stack retrieved above will be used. + ADR_REL x3, __boot_core_stack_end_exclusive + mov sp, x3 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x4, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x5, CNTFRQ_EL0 + cmp x5, xzr + b.eq .L_parking_loop + str w5, [x4] + + // Jump to Rust code. x0, x1 and x2 hold the function arguments provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/cpu/smp.rs b/19_kernel_heap/kernel/src/_arch/aarch64/cpu/smp.rs new file mode 100644 index 000000000..491920389 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/exception.rs b/19_kernel_heap/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..ab4640815 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,325 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use crate::{exception, memory, symbols}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!( + include_str!("exception.s"), + CONST_ESR_EL1_EC_SHIFT = const 26, + CONST_ESR_EL1_EC_VALUE_SVC64 = const 0x15 +); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!( + f, + " Symbol: {}", + match symbols::lookup_symbol(memory::Address::new(self.elr_el1 as usize)) { + Some(sym) => sym.name(), + _ => "Symbol not found", + } + )?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/exception.s b/19_kernel_heap/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..cdef8c586 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2022 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler is_lower_el is_sync +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 18 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // Build a stack frame for backtracing. +.if \is_lower_el == 1 + // If we came from a lower EL, make it a root frame (by storing zero) so that the kernel + // does not attempt to trace into userspace. + stp xzr, xzr, [sp, #16 * 17] +.else + // For normal branches, the link address points to the instruction to be executed _after_ + // returning from a branch. In a backtrace, we want to show the instruction that caused the + // branch, though. That is why code in backtrace.rs subtracts 4 (length of one instruction) + // from the link address. + // + // Here we have a special case, though, because ELR_EL1 is used instead of LR to build the + // stack frame, so that it becomes possible to trace beyond an exception. Hence, it must be + // considered that semantics for ELR_EL1 differ from case to case. + // + // Unless an "exception generating instruction" was executed, ELR_EL1 already points to the + // the correct instruction, and hence the subtraction by 4 in backtrace.rs would yield wrong + // results. To cover for this, 4 is added to ELR_EL1 below unless the cause of exception was + // an SVC instruction. BRK and HLT are "exception generating instructions" as well, but they + // are not expected and therefore left out for now. + // + // For reference: Search for "preferred exception return address" in the Architecture + // Reference Manual for ARMv8-A. +.if \is_sync == 1 + lsr w3, w3, {CONST_ESR_EL1_EC_SHIFT} // w3 = ESR_EL1.EC + cmp w3, {CONST_ESR_EL1_EC_VALUE_SVC64} // w3 == SVC64 ? + b.eq 1f +.endif + add x1, x1, #4 +1: + stp x29, x1, [sp, #16 * 17] +.endif + + // Set the frame pointer to the stack frame record. + add x29, sp, #16 * 17 + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous, 0, 1 +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq, 0, 0 +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror, 0, 0 + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous, 0, 1 +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq, 0, 0 +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror, 0, 0 + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous, 1, 1 +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq, 1, 0 +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror, 1, 0 + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous, 1, 0 +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq, 1, 0 +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror, 1, 0 +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 18 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/exception/asynchronous.rs b/19_kernel_heap/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..811ef138e --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/memory/mmu.rs b/19_kernel_heap/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..984b2e04f --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::{mmu::TranslationGranule, Address, Physical}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + #[inline(always)] + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + #[inline(always)] + fn configure_translation_control(&self) { + let t1sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI1::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG1::KiB_64 + + TCR_EL1::SH1::Inner + + TCR_EL1::ORGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD1::EnableTTBR1Walks + + TCR_EL1::A1::TTBR1 + + TCR_EL1::T1SZ.val(t1sz) + + TCR_EL1::EPD0::DisableTTBR0Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Set the "Translation Table Base Register". + TTBR1_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/19_kernel_heap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..21fae3b82 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,521 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, + memory::{ + self, + mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, + }, + Address, Physical, Virtual, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn virt_start_addr(&self) -> Address; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], + + /// Have the tables been initialized? + initialized: bool, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl StartAddr for [T; N] { + fn virt_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +/// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. +impl convert::TryFrom> for AttributeFields { + type Error = &'static str; + + fn try_from( + desc: InMemoryRegister, + ) -> Result { + let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { + memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, + memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, + _ => return Err("Unexpected memory attribute"), + }; + + let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, + _ => return Err("Unexpected access permission"), + }; + + let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; + + Ok(AttributeFields { + mem_attributes, + acc_perms, + execute_never, + }) + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_page_addr( + phys_output_page_addr: PageAddress, + attribute_fields: &AttributeFields, + ) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } + + /// Returns the valid bit. + fn is_valid(&self) -> bool { + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } + + /// Returns the output page. + fn output_page_addr(&self) -> PageAddress { + let shifted = InMemoryRegister::::new(self.value) + .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; + + PageAddress::from(shifted << Granule64KiB::SHIFT) + } + + /// Returns the attributes. + fn try_attributes(&self) -> Result { + InMemoryRegister::::new(self.value).try_into() + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromTop = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; + + type TableStartFromBottom = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; +} + +impl + FixedSizeTranslationTable +{ + const START_FROM_TOP_OFFSET: Address = + Address::new((usize::MAX - (Granule512MiB::SIZE * NUM_TABLES)) + 1); + + /// Create an instance. + #[allow(clippy::assertions_on_constants)] + const fn _new(for_precompute: bool) -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + initialized: for_precompute, + } + } + + pub const fn new_for_precompute() -> Self { + Self::_new(true) + } + + #[cfg(test)] + pub fn new_for_runtime() -> Self { + Self::_new(false) + } + + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { + let mut addr = virt_page_addr.into_inner(); + + if START_FROM_TOP { + addr = addr - Self::START_FROM_TOP_OFFSET; + } + + let lvl2_index = addr.as_usize() >> Granule512MiB::SHIFT; + let lvl3_index = (addr.as_usize() & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); + } + + Ok((lvl2_index, lvl3_index)) + } + + /// Returns the PageDescriptor corresponding to the supplied page address. + #[inline(always)] + fn page_descriptor_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<&PageDescriptor, &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &self.lvl3[lvl2_index][lvl3_index]; + + Ok(desc) + } + + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. + #[inline(always)] + fn set_page_descriptor_from_page_addr( + &mut self, + virt_page_addr: PageAddress, + new_desc: &PageDescriptor, + ) -> Result<(), &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &mut self.lvl3[lvl2_index][lvl3_index]; + + if desc.is_valid() { + return Err("Virtual page is already mapped"); + } + + *desc = *new_desc; + Ok(()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl + memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable +{ + fn init(&mut self) -> Result<(), &'static str> { + if self.initialized { + return Ok(()); + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { + let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); + let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; + + Ok(()) + } + + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + assert!(self.initialized, "Translation tables not initialized"); + + if virt_region.size() != phys_region.size() { + return Err("Tried to map memory regions with unequal sizes"); + } + + if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() + { + return Err("Tried to map outside of physical address space"); + } + + let iter = phys_region.into_iter().zip(virt_region.into_iter()); + for (phys_page_addr, virt_page_addr) in iter { + let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); + let virt_page = virt_page_addr; + + self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; + } + + Ok(()) + } + + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str> { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + Ok(page_desc.output_page_addr()) + } + + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + page_desc.try_attributes() + } + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str> { + let virt_page = PageAddress::from(virt_addr.align_down_page()); + let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; + + Ok(phys_page.into_inner() + virt_addr.offset_into_page()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1, true>; + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/19_kernel_heap/kernel/src/_arch/aarch64/time.rs b/19_kernel_heap/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..ee1c3ef72 --- /dev/null +++ b/19_kernel_heap/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/19_kernel_heap/kernel/src/backtrace.rs b/19_kernel_heap/kernel/src/backtrace.rs new file mode 100644 index 000000000..a6af2fccc --- /dev/null +++ b/19_kernel_heap/kernel/src/backtrace.rs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Backtracing support. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/backtrace.rs"] +mod arch_backtrace; + +use crate::{ + memory::{Address, Virtual}, + symbols, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +pub use arch_backtrace::{corrupt_link, corrupt_previous_frame_addr}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A backtrace item. +#[allow(missing_docs)] +pub enum BacktraceItem { + InvalidFramePointer(Address), + InvalidLink(Address), + Link(Address), +} + +/// Pseudo-struct for printing a backtrace using its fmt::Display implementation. +pub struct Backtrace; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for Backtrace { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "Backtrace:")?; + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + )?; + writeln!( + f, + " Address Function containing address" + )?; + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + )?; + + let mut fmt_res: fmt::Result = Ok(()); + let trace_formatter = + |maybe_iter: Option<&mut dyn Iterator>| match maybe_iter { + None => fmt_res = writeln!(f, "ERROR! No valid stack frame found"), + Some(iter) => { + // Since the backtrace is printed, the first function is always + // core::fmt::write. Skip 1 so it is excluded and doesn't bloat the output. + for (i, backtrace_res) in iter.skip(1).enumerate() { + match backtrace_res { + BacktraceItem::InvalidFramePointer(addr) => { + fmt_res = writeln!( + f, + " {:>2}. ERROR! \ + Encountered invalid frame pointer ({}) during backtrace", + i + 1, + addr + ); + } + BacktraceItem::InvalidLink(addr) => { + fmt_res = writeln!( + f, + " {:>2}. ERROR! \ + Link address ({}) is not contained in kernel .text section", + i + 1, + addr + ); + } + BacktraceItem::Link(addr) => { + fmt_res = writeln!( + f, + " {:>2}. {:016x} | {:<50}", + i + 1, + addr.as_usize(), + match symbols::lookup_symbol(addr) { + Some(sym) => sym.name(), + _ => "Symbol not found", + } + ) + } + }; + + if fmt_res.is_err() { + break; + } + } + } + }; + + arch_backtrace::backtrace(trace_formatter); + fmt_res?; + + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + ) + } +} diff --git a/19_kernel_heap/kernel/src/bsp.rs b/19_kernel_heap/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/19_kernel_heap/kernel/src/bsp/device_driver.rs b/19_kernel_heap/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..2dfaec8d6 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(feature = "bsp_rpi4")] +mod arm; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/arm.rs b/19_kernel_heap/kernel/src/bsp/device_driver/arm.rs new file mode 100644 index 000000000..8d1cbfbd8 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2.rs b/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2.rs new file mode 100644 index 000000000..7dabf7934 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; +use alloc::vec::Vec; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = Vec>>; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 1019; + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new( + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, + ) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new(Vec::new()), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.handler_table + .write(|table| table.resize(IRQNumber::MAX_INCLUSIVE + 1, None)); + + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs b/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs new file mode 100644 index 000000000..0fd16bb38 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs b/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs new file mode 100644 index 000000000..1fc9d70e9 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, + state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num % 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/bcm.rs b/19_kernel_heap/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..7b7c288b7 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..812156f44 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs new file mode 100644 index 000000000..66c395972 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.periph.init(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.periph.print_handler(); + } +} diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs new file mode 100644 index 000000000..029c1e742 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use alloc::vec::Vec; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = Vec>>; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new(Vec::new()), + } + } + + /// Called by the kernel to bring up the device. + pub fn init(&self) { + self.handler_table + .write(|table| table.resize(PeripheralIRQ::MAX_INCLUSIVE + 1, None)); + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() % 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..3d5809755 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,516 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Send a slice of characters. + fn write_array(&mut self, a: &[char]) { + for c in a { + self.write_char(*c); + } + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_array(&self, a: &[char]) { + self.inner.lock(|inner| inner.write_array(a)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff --git a/19_kernel_heap/kernel/src/bsp/device_driver/common.rs b/19_kernel_heap/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..3ce1d8d81 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use crate::memory::{Address, Virtual}; +use core::{fmt, marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: Address, + phantom: PhantomData T>, +} + +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: Address) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr.as_usize() as *const _) } + } +} + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi.rs b/19_kernel_heap/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..30421dfa6 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi/cpu.rs b/19_kernel_heap/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi/driver.rs b/19_kernel_heap/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..a1f55b170 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, + memory, + memory::mmu::MMIODescriptor, +}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering}, +}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi3")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi4")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the UART driver. +unsafe fn post_init_uart() -> Result<(), &'static str> { + console::register_console(PL011_UART.assume_init_ref()); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_gpio() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; + + GPIO.write(device_driver::GPIO::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +unsafe fn post_init_gpio() -> Result<(), &'static str> { + GPIO.assume_init_ref().map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi3")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &periph_mmio_descriptor, + )?; + + INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi4")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); + let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; + + let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); + let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; + + INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the interrupt controller driver. +unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_gpio() -> Result<(), &'static str> { + instantiate_gpio()?; + + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( + GPIO.assume_init_ref(), + Some(post_init_gpio), + None, + ); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { + instantiate_interrupt_controller()?; + + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + INTERRUPT_CONTROLLER.assume_init_ref(), + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + use crate::cpu; + + unsafe { + instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); + console::register_console(PL011_UART.assume_init_ref()); + }; +} diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi/exception.rs b/19_kernel_heap/kernel/src/bsp/raspberrypi/exception.rs new file mode 100644 index 000000000..a9eaa6ac4 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/19_kernel_heap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs new file mode 100644 index 000000000..776182fd0 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +#[cfg(feature = "bsp_rpi3")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; + + pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +#[cfg(feature = "bsp_rpi4")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::IRQNumber; + + pub const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi/kernel.ld b/19_kernel_heap/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..2408b63cd --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,134 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +INCLUDE kernel_virt_addr_space_size.ld; + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +/* The kernel's virtual address range will be: + * + * [END_ADDRESS_INCLUSIVE, START_ADDRESS] + * [u64::MAX , (u64::MAX - __kernel_virt_addr_space_size) + 1] + */ +__kernel_virt_start_addr = ((0xffffffffffffffff - __kernel_virt_addr_space_size) + 1); + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); + segment_heap PT_LOAD FLAGS(6); + segment_boot_core_stack PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __kernel_virt_start_addr; + + ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : AT(__rpi_phys_binary_load_addr) + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + .kernel_symbols : ALIGN(8) { + __kernel_symbols_start = .; + . += 32 * 1024; + } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + __data_start = .; + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + + /*********************************************************************************************** + * Heap + ***********************************************************************************************/ + __heap_start = .; + .heap (NOLOAD) : + { + . += 16 * 1024 * 1024; + } :segment_heap + __heap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "Heap is not page aligned") + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + + /*********************************************************************************************** + * Guard Page + ***********************************************************************************************/ + . += PAGE_SIZE; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) + { + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld b/19_kernel_heap/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld new file mode 100644 index 000000000..c5d58c30a --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld @@ -0,0 +1 @@ +__kernel_virt_addr_space_size = 1024 * 1024 * 1024 diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi/memory.rs b/19_kernel_heap/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..8507dfc7e --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | .kernel_symbols | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | heap_start == data_end_exclusive +//! | .heap | +//! | | +//! +---------------------------------------+ +//! | | heap_end_exclusive +//! | | +//! +//! +//! +//! +//! +//! The virtual memory layout is as follows: +//! +//! +---------------------------------------+ +//! | | code_start @ __kernel_virt_start_addr +//! | .text | +//! | .rodata | +//! | .got | +//! | .kernel_symbols | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | heap_start == data_end_exclusive +//! | .heap | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_start == heap_end_exclusive +//! | VA region for MMIO remapping | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_end_exclusive +//! | Unmapped guard page | +//! | | +//! +---------------------------------------+ +//! | | boot_core_stack_start +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | boot_core_stack_end_exclusive +//! | | +pub mod mmu; + +use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; + + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + + static __heap_start: UnsafeCell<()>; + static __heap_end_exclusive: UnsafeCell<()>; + + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + + static __boot_core_stack_start: UnsafeCell<()>; + static __boot_core_stack_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + use super::*; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); + pub const PERIPHERAL_IC_SIZE: usize = 0x24; + + pub const GPIO_START: Address = Address::new(0x3F20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const END: Address = Address::new(0x4001_0000); + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const GPIO_START: Address = Address::new(0xFE20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0xFE20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const GICD_START: Address = Address::new(0xFF84_1000); + pub const GICD_SIZE: usize = 0x824; + + pub const GICC_START: Address = Address::new(0xFF84_2000); + pub const GICC_SIZE: usize = 0x14; + + pub const END: Address = Address::new(0xFF85_0000); + } + + pub const END: Address = mmio::END; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_code_start() -> PageAddress { + PageAddress::from(unsafe { __code_start.get() as usize }) +} + +/// Size of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_size() -> usize { + unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } +} + +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { + PageAddress::from(unsafe { __data_start.get() as usize }) +} + +/// Size of the data segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn data_size() -> usize { + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } +} + +/// Start page address of the heap segment. +#[inline(always)] +fn virt_heap_start() -> PageAddress { + PageAddress::from(unsafe { __heap_start.get() as usize }) +} + +/// Size of the heap segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn heap_size() -> usize { + unsafe { (__heap_end_exclusive.get() as usize) - (__heap_start.get() as usize) } +} + +/// Start page address of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_mmio_remap_start() -> PageAddress { + PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) +} + +/// Size of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn mmio_remap_size() -> usize { + unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } +} + +/// Start page address of the boot core's stack. +#[inline(always)] +fn virt_boot_core_stack_start() -> PageAddress { + PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) +} + +/// Size of the boot core's stack. +#[inline(always)] +fn boot_core_stack_size() -> usize { + unsafe { + (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Exclusive end address of the physical address space. +#[inline(always)] +pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { + PageAddress::from(map::END) +} diff --git a/19_kernel_heap/kernel/src/bsp/raspberrypi/memory/mmu.rs b/19_kernel_heap/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..ef52e3686 --- /dev/null +++ b/19_kernel_heap/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use crate::{ + memory::{ + mmu::{ + self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, + MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type KernelTranslationTable = + ::TableStartFromTop; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to +/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. +pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + +/// The kernel's virtual address space defined by this BSP. +pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// It is mandatory that InitStateLock is transparent. +/// +/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. +/// There is a unit tests that checks this porperty. +#[link_section = ".data"] +#[no_mangle] +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new_for_precompute()); + +/// This value is needed during early boot for MMU setup. +/// +/// This will be patched to the correct value by the "translation table tool" after linking. This +/// given value here is just a dummy. +#[link_section = ".text._start_arguments"] +#[no_mangle] +static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This is a hack for retrieving the value for the kernel's virtual address space size as a +/// constant from a common place, since it is needed as a compile-time/link-time constant in both, +/// the linker script and the Rust sources. +#[allow(clippy::needless_late_init)] +const fn kernel_virt_addr_space_size() -> usize { + let __kernel_virt_addr_space_size; + + include!("../kernel_virt_addr_space_size.ld"); + + __kernel_virt_addr_space_size +} + +/// Helper function for calculating the number of pages the given parameter spans. +const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); + assert!(size % KernelGranule::SIZE == 0); + + size >> KernelGranule::SHIFT +} + +/// The data pages of the kernel binary. +fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); + + let start_page_addr = super::virt_data_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +// There is no reason to expect the following conversions to fail, since they were generated offline +// by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. +fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { + let phys_start_page_addr = + generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) + .unwrap(); + + let phys_end_exclusive_page_addr = phys_start_page_addr + .checked_offset(virt_region.num_pages() as isize) + .unwrap(); + + MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) +} + +fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { + generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The code pages of the kernel binary. +pub fn virt_code_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::code_size()); + + let start_page_addr = super::virt_code_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The heap pages. +pub fn virt_heap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::heap_size()); + + let start_page_addr = super::virt_heap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The boot core stack pages. +pub fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); + + let start_page_addr = super::virt_boot_core_stack_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} + +/// The MMIO remap pages. +pub fn virt_mmio_remap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::mmio_remap_size()); + + let start_page_addr = super::virt_mmio_remap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Add mapping records for the kernel binary. +/// +/// The actual translation table entries for the kernel binary are generated using the offline +/// `translation table tool` and patched into the kernel binary. This function just adds the mapping +/// record entries. +pub fn kernel_add_mapping_records_for_precomputed() { + let virt_code_region = virt_code_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel code and RO data", + &virt_code_region, + &kernel_virt_to_phys_region(virt_code_region), + &kernel_page_attributes(virt_code_region.start_page_addr()), + ); + + let virt_data_region = virt_data_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel data and bss", + &virt_data_region, + &kernel_virt_to_phys_region(virt_data_region), + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); + + let virt_heap_region = virt_heap_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel heap", + &virt_heap_region, + &kernel_virt_to_phys_region(virt_heap_region), + &kernel_page_attributes(virt_heap_region.start_page_addr()), + ); + + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", + &virt_boot_core_stack_region, + &kernel_virt_to_phys_region(virt_boot_core_stack_region), + &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), + ); +} diff --git a/19_kernel_heap/kernel/src/common.rs b/19_kernel_heap/kernel/src/common.rs new file mode 100644 index 000000000..2ad7e4c1e --- /dev/null +++ b/19_kernel_heap/kernel/src/common.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Check if a value is aligned to a given size. +#[inline(always)] +pub const fn is_aligned(value: usize, alignment: usize) -> bool { + assert!(alignment.is_power_of_two()); + + (value & (alignment - 1)) == 0 +} + +/// Align down. +#[inline(always)] +pub const fn align_down(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + value & !(alignment - 1) +} + +/// Align up. +#[inline(always)] +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + (value + alignment - 1) & !(alignment - 1) +} + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/19_kernel_heap/kernel/src/console.rs b/19_kernel_heap/kernel/src/console.rs new file mode 100644 index 000000000..5efa9395b --- /dev/null +++ b/19_kernel_heap/kernel/src/console.rs @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod buffer_console; + +use crate::synchronization; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a slice of characters. + fn write_array(&self, a: &[char]); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&buffer_console::BUFFER_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); + + static FIRST_SWITCH: InitStateLock = InitStateLock::new(true); + FIRST_SWITCH.write(|first| { + if *first { + *first = false; + + buffer_console::BUFFER_CONSOLE.dump(); + } + }); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.read(|con| *con) +} diff --git a/19_kernel_heap/kernel/src/console/buffer_console.rs b/19_kernel_heap/kernel/src/console/buffer_console.rs new file mode 100644 index 000000000..05903e7cf --- /dev/null +++ b/19_kernel_heap/kernel/src/console/buffer_console.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A console that buffers input during the init phase. + +use super::interface; +use crate::{console, info, synchronization, synchronization::InitStateLock}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const BUF_SIZE: usize = 1024 * 64; + +pub struct BufferConsoleInner { + buf: [char; BUF_SIZE], + write_ptr: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct BufferConsole { + inner: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static BUFFER_CONSOLE: BufferConsole = BufferConsole { + inner: InitStateLock::new(BufferConsoleInner { + // Use the null character, so this lands in .bss and does not waste space in the binary. + buf: ['\0'; BUF_SIZE], + write_ptr: 0, + }), +}; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl BufferConsoleInner { + fn write_char(&mut self, c: char) { + if self.write_ptr < (BUF_SIZE - 1) { + self.buf[self.write_ptr] = c; + self.write_ptr += 1; + } + } +} + +impl fmt::Write for BufferConsoleInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +impl BufferConsole { + /// Dump the buffer. + /// + /// # Invariant + /// + /// It is expected that this is only called when self != crate::console::console(). + pub fn dump(&self) { + self.inner.read(|inner| { + console::console().write_array(&inner.buf[0..inner.write_ptr]); + + if inner.write_ptr == (BUF_SIZE - 1) { + info!("Pre-UART buffer overflowed"); + } else if inner.write_ptr > 0 { + info!("End of pre-UART buffer") + } + }); + } +} + +impl interface::Write for BufferConsole { + fn write_char(&self, c: char) { + self.inner.write(|inner| inner.write_char(c)); + } + + fn write_array(&self, _a: &[char]) {} + + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result { + self.inner.write(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) {} +} + +impl interface::Read for BufferConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for BufferConsole {} +impl interface::All for BufferConsole {} diff --git a/19_kernel_heap/kernel/src/cpu.rs b/19_kernel_heap/kernel/src/cpu.rs new file mode 100644 index 000000000..8716a918b --- /dev/null +++ b/19_kernel_heap/kernel/src/cpu.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +pub mod smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/19_kernel_heap/kernel/src/cpu/boot.rs b/19_kernel_heap/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/19_kernel_heap/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/19_kernel_heap/kernel/src/cpu/smp.rs b/19_kernel_heap/kernel/src/cpu/smp.rs new file mode 100644 index 000000000..de612d589 --- /dev/null +++ b/19_kernel_heap/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff --git a/19_kernel_heap/kernel/src/driver.rs b/19_kernel_heap/kernel/src/driver.rs new file mode 100644 index 000000000..88b41b818 --- /dev/null +++ b/19_kernel_heap/kernel/src/driver.rs @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, +}; +use alloc::vec::Vec; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager +where + T: 'static, +{ + descriptors: InitStateLock>>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + irq_number, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager +where + T: fmt::Display, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + descriptors: InitStateLock::new(Vec::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.descriptors + .write(|descriptors| descriptors.push(descriptor)); + } + + /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { + self.descriptors.read(|descriptors| { + for descriptor in descriptors { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + } + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + for descriptor in descriptors { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + } + }) + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + self.descriptors.read(|descriptors| { + for (i, desc) in descriptors.iter().enumerate() { + info!(" {}. {}", i + 1, desc.device_driver.compatible()); + } + }); + } +} diff --git a/19_kernel_heap/kernel/src/exception.rs b/19_kernel_heap/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/19_kernel_heap/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/19_kernel_heap/kernel/src/exception/asynchronous.rs b/19_kernel_heap/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..2c874dd60 --- /dev/null +++ b/19_kernel_heap/kernel/src/exception/asynchronous.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff --git a/19_kernel_heap/kernel/src/exception/asynchronous/null_irq_manager.rs b/19_kernel_heap/kernel/src/exception/asynchronous/null_irq_manager.rs new file mode 100644 index 000000000..38919ffe4 --- /dev/null +++ b/19_kernel_heap/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff --git a/19_kernel_heap/kernel/src/lib.rs b/19_kernel_heap/kernel/src/lib.rs new file mode 100644 index 000000000..317bcc727 --- /dev/null +++ b/19_kernel_heap/kernel/src/lib.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(alloc_error_handler)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(generic_const_exprs)] +#![feature(int_roundings)] +#![feature(is_sorted)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(step_trait)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +extern crate alloc; + +mod panic_wait; +mod synchronization; + +pub mod backtrace; +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod state; +pub mod symbols; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/19_kernel_heap/kernel/src/main.rs b/19_kernel_heap/kernel/src/main.rs new file mode 100644 index 000000000..ae2ea8a7b --- /dev/null +++ b/19_kernel_heap/kernel/src/main.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +extern crate alloc; + +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + +/// Early init code. +/// +/// When this code runs, virtual memory is already enabled. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - Printing will not work until the respective driver's MMIO is remapped. +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + + bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online:"); + memory::mmu::kernel_print_mappings(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + + info!("Kernel heap:"); + memory::heap_alloc::kernel_heap_allocator().print_usage(); + + info!("Echoing input now"); + cpu::wait_forever(); +} diff --git a/19_kernel_heap/kernel/src/memory.rs b/19_kernel_heap/kernel/src/memory.rs new file mode 100644 index 000000000..bc6113366 --- /dev/null +++ b/19_kernel_heap/kernel/src/memory.rs @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod heap_alloc; +pub mod mmu; + +use crate::{bsp, common}; +use core::{ + fmt, + marker::PhantomData, + ops::{Add, Sub}, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Physical {} + +/// Zero-sized type to mark a virtual address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl AddressType for Physical {} +impl AddressType for Virtual {} + +impl Address { + /// Create an instance. + pub const fn new(value: usize) -> Self { + Self { + value, + _address_type: PhantomData, + } + } + + /// Convert to usize. + pub const fn as_usize(self) -> usize { + self.value + } + + /// Align down to page size. + #[must_use] + pub const fn align_down_page(self) -> Self { + let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Align up to page size. + #[must_use] + pub const fn align_up_page(self) -> Self { + let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Checks if the address is page aligned. + pub const fn is_page_aligned(&self) -> bool { + common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) + } + + /// Return the address' offset into the corresponding page. + pub const fn offset_into_page(&self) -> usize { + self.value & bsp::memory::mmu::KernelGranule::MASK + } +} + +impl Add for Address { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: usize) -> Self::Output { + match self.value.checked_add(rhs) { + None => panic!("Overflow on Address::add"), + Some(x) => Self::new(x), + } + } +} + +impl Sub for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: usize) -> Self::Output { + match self.value.checked_sub(rhs) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl Sub> for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Address) -> Self::Output { + match self.value.checked_sub(rhs.value) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl Address { + /// Checks if the address is part of the boot core stack region. + pub fn is_valid_stack_addr(&self) -> bool { + bsp::memory::mmu::virt_boot_core_stack_region().contains(*self) + } + + /// Checks if the address is part of the kernel code region. + pub fn is_valid_code_addr(&self) -> bool { + bsp::memory::mmu::virt_code_region().contains(*self) + } +} + +impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q3: u8 = ((self.value >> 32) & 0xff) as u8; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:02x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q4: u16 = ((self.value >> 48) & 0xffff) as u16; + let q3: u16 = ((self.value >> 32) & 0xffff) as u16; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:04x}_", q4)?; + write!(f, "{:04x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); + heap_alloc::kernel_init_heap_allocator(); +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of [Address] methods. + #[kernel_test] + fn address_type_method_sanity() { + let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); + + assert_eq!( + addr.align_down_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE + ); + + assert_eq!( + addr.align_up_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + + assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} diff --git a/19_kernel_heap/kernel/src/memory/heap_alloc.rs b/19_kernel_heap/kernel/src/memory/heap_alloc.rs new file mode 100644 index 000000000..cf4298fa4 --- /dev/null +++ b/19_kernel_heap/kernel/src/memory/heap_alloc.rs @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Heap allocation. + +use crate::{ + backtrace, bsp, common, debug, info, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, + warn, +}; +use alloc::alloc::{GlobalAlloc, Layout}; +use core::sync::atomic::{AtomicBool, Ordering}; +use linked_list_allocator::Heap as LinkedListHeap; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A heap allocator that can be lazyily initialized. +pub struct HeapAllocator { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +#[global_allocator] +static KERNEL_HEAP_ALLOCATOR: HeapAllocator = HeapAllocator::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +#[inline(always)] +fn debug_print_alloc_dealloc(operation: &'static str, ptr: *mut u8, layout: Layout) { + let size = layout.size(); + let (size_h, size_unit) = common::size_human_readable_ceil(size); + let addr = Address::::new(ptr as usize); + + debug!( + "Kernel Heap: {}\n \ + Size: {:#x} ({} {})\n \ + Start: {}\n \ + End excl: {}\n\n \ + {}", + operation, + size, + size_h, + size_unit, + addr, + addr + size, + backtrace::Backtrace + ); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +#[alloc_error_handler] +fn alloc_error_handler(layout: Layout) -> ! { + panic!("Allocation error: {:?}", layout) +} + +/// Return a reference to the kernel's heap allocator. +pub fn kernel_heap_allocator() -> &'static HeapAllocator { + &KERNEL_HEAP_ALLOCATOR +} + +impl HeapAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: IRQSafeNullLock::new(LinkedListHeap::empty()), + } + } + + /// Print the current heap usage. + pub fn print_usage(&self) { + let (used, free) = KERNEL_HEAP_ALLOCATOR + .inner + .lock(|inner| (inner.used(), inner.free())); + + if used >= 1024 { + let (used_h, used_unit) = common::size_human_readable_ceil(used); + info!(" Used: {} Byte ({} {})", used, used_h, used_unit); + } else { + info!(" Used: {} Byte", used); + } + + if free >= 1024 { + let (free_h, free_unit) = common::size_human_readable_ceil(free); + info!(" Free: {} Byte ({} {})", free, free_h, free_unit); + } else { + info!(" Free: {} Byte", free); + } + } +} + +unsafe impl GlobalAlloc for HeapAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let result = KERNEL_HEAP_ALLOCATOR + .inner + .lock(|inner| inner.allocate_first_fit(layout).ok()); + + match result { + None => core::ptr::null_mut(), + Some(allocation) => { + let ptr = allocation.as_ptr(); + + debug_print_alloc_dealloc("Allocation", ptr, layout); + + ptr + } + } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + KERNEL_HEAP_ALLOCATOR + .inner + .lock(|inner| inner.deallocate(core::ptr::NonNull::new_unchecked(ptr), layout)); + + debug_print_alloc_dealloc("Free", ptr, layout); + } +} + +/// Query the BSP for the heap region and initialize the kernel's heap allocator with it. +pub fn kernel_init_heap_allocator() { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + warn!("Already initialized"); + return; + } + + let region = bsp::memory::mmu::virt_heap_region(); + + KERNEL_HEAP_ALLOCATOR.inner.lock(|inner| unsafe { + inner.init(region.start_addr().as_usize() as *mut u8, region.size()) + }); + + INIT_DONE.store(true, Ordering::Relaxed); +} diff --git a/19_kernel_heap/kernel/src/memory/mmu.rs b/19_kernel_heap/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..abe3b1813 --- /dev/null +++ b/19_kernel_heap/kernel/src/memory/mmu.rs @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod mapping_record; +mod page_alloc; +mod translation_table; +mod types; + +use crate::{ + bsp, + memory::{Address, Physical, Virtual}, + synchronization::{self, interface::Mutex}, +}; +use core::{fmt, num::NonZeroUsize}; + +pub use types::*; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Turns on the MMU for the first time and enables data and instruction caching. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] + type TableStartFromTop; + + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +use interface::MMU; +use synchronization::interface::ReadWriteEx; +use translation_table::interface::TranslationTable; + +/// Map a region in the kernel's translation tables. +/// +/// No input checks done, input is passed through to the architectural implementation. +/// +/// # Safety +/// +/// - See `map_at()`. +/// - Does not prevent aliasing. +unsafe fn kernel_map_at_unchecked( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + + kernel_add_mapping_record(name, virt_region, phys_region, attr); + + Ok(()) +} + +/// Try to translate a kernel virtual address to a physical address. +/// +/// Will only succeed if there exists a valid mapping for the input address. +fn try_kernel_virt_addr_to_phys_addr( + virt_addr: Address, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's mask. + pub const MASK: usize = Self::SIZE - 1; + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +pub fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Add an entry to the mapping info record. +pub fn kernel_add_mapping_record( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) { + mapping_record::kernel_add(name, virt_region, phys_region, attr); +} + +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +/// +/// # Safety +/// +/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + let phys_region = MemoryRegion::from(*mmio_descriptor); + let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); + + // Check if an identical region has been mapped for another driver. If so, reuse it. + let virt_addr = if let Some(addr) = + mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) + { + addr + // Otherwise, allocate a new region and map it. + } else { + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, + }; + + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + virt_region.start_addr() + }; + + Ok(virt_addr + offset_into_start_page) +} + +/// Try to translate a kernel virtual page address to a physical page address. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_virt_page_addr_to_phys_page_addr( + virt_page_addr: PageAddress, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) +} + +/// Try to get the attributes of a kernel page. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_page_attributes( + virt_page_addr: PageAddress, +) -> Result { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_page_attributes(virt_page_addr)) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() +} + +/// Enable the MMU and data + instruction caching. +/// +/// # Safety +/// +/// - Crucial function during kernel init. Changes the the complete memory view of the processor. +#[inline(always)] +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) +} diff --git a/19_kernel_heap/kernel/src/memory/mmu/mapping_record.rs b/19_kernel_heap/kernel/src/memory/mmu/mapping_record.rs new file mode 100644 index 000000000..9c17258d1 --- /dev/null +++ b/19_kernel_heap/kernel/src/memory/mmu/mapping_record.rs @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + +use super::{ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock}; +use alloc::{vec, vec::Vec}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Type describing a virtual memory mapping. +#[allow(missing_docs)] +struct MappingRecordEntry { + pub users: Vec<&'static str>, + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, + pub attribute_fields: AttributeFields, +} + +struct MappingRecord { + inner: Vec, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MAPPING_RECORD: InitStateLock = + InitStateLock::new(MappingRecord::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl MappingRecordEntry { + pub fn new( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Self { + Self { + users: vec![name], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), + attribute_fields: *attr, + } + } + + pub fn add_user(&mut self, user: &'static str) { + self.users.push(user); + } +} + +impl MappingRecord { + pub const fn new() -> Self { + Self { inner: Vec::new() } + } + + fn sort(&mut self) { + if !self.inner.is_sorted_by_key(|item| item.virt_start_addr) { + self.inner.sort_unstable_by_key(|item| item.virt_start_addr) + } + } + + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { + return false; + } + + if x.num_pages != phys_region.num_pages() { + return false; + } + + true + }) + } + + pub fn add( + &mut self, + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) { + self.inner.push(MappingRecordEntry::new( + name, + virt_region, + phys_region, + attr, + )); + + self.sort(); + } + + pub fn print(&self) { + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", + "Virtual", "Physical", "Size", "Attr", "Entity" + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + + for i in self.inner.iter() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match i.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if i.attribute_fields.execute_never { + "XN" + } else { + "X" + }; + + info!( + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, + phys_end_inclusive, + size, + unit, + attr, + acc_p, + xn, + i.users[0] + ); + + for k in &i.users[1..] { + info!( + " | {}", + k + ); + } + } + + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +/// Add an entry to the mapping info record. +pub fn kernel_add( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) +} + +pub fn kernel_find_and_insert_mmio_duplicate( + mmio_descriptor: &MMIODescriptor, + new_user: &'static str, +) -> Option> { + let phys_region: MemoryRegion = (*mmio_descriptor).into(); + + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + + dup.add_user(new_user); + + Some(dup.virt_start_addr) + }) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print() { + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} diff --git a/19_kernel_heap/kernel/src/memory/mmu/page_alloc.rs b/19_kernel_heap/kernel/src/memory/mmu/page_alloc.rs new file mode 100644 index 000000000..344afd200 --- /dev/null +++ b/19_kernel_heap/kernel/src/memory/mmu/page_alloc.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Page allocation. + +use super::MemoryRegion; +use crate::{ + memory::{AddressType, Virtual}, + synchronization::IRQSafeNullLock, + warn, +}; +use core::num::NonZeroUsize; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A page allocator that can be lazyily initialized. +pub struct PageAllocator { + pool: Option>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = + IRQSafeNullLock::new(PageAllocator::new()); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's MMIO virtual address allocator. +pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { + &KERNEL_MMIO_VA_ALLOCATOR +} + +impl PageAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { pool: None } + } + + /// Initialize the allocator. + pub fn init(&mut self, pool: MemoryRegion) { + if self.pool.is_some() { + warn!("Already initialized"); + return; + } + + self.pool = Some(pool); + } + + /// Allocate a number of pages. + pub fn alloc( + &mut self, + num_requested_pages: NonZeroUsize, + ) -> Result, &'static str> { + if self.pool.is_none() { + return Err("Allocator not initialized"); + } + + self.pool + .as_mut() + .unwrap() + .take_first_n_pages(num_requested_pages) + } +} diff --git a/19_kernel_heap/kernel/src/memory/mmu/translation_table.rs b/19_kernel_heap/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..341ffc5c8 --- /dev/null +++ b/19_kernel_heap/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +use super::{AttributeFields, MemoryRegion}; +use crate::memory::{Address, Physical, Virtual}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(target_arch = "aarch64")] +pub use arch_translation_table::FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Translation table interfaces. +pub mod interface { + use crate::memory::mmu::PageAddress; + + use super::*; + + /// Translation table operations. + pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self) -> Result<(), &'static str>; + + /// Map the given virtual memory region to the given physical memory region. + /// + /// # Safety + /// + /// - Using wrong attributes can cause multiple issues of different nature in the system. + /// - It is not required that the architectural implementation prevents aliasing. That is, + /// mapping to the same physical memory using multiple virtual addresses, which would + /// break Rust's ownership assumptions. This should be protected against in the kernel's + /// generic MMU code. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; + + /// Try to translate a virtual page address to a physical page address. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str>; + + /// Try to get the attributes of a page. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result; + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str>; + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use arch_translation_table::MinSizeTranslationTable; + use interface::TranslationTable; + use test_macros::kernel_test; + + /// Sanity checks for the TranslationTable implementation. + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. + let mut tables = MinSizeTranslationTable::new_for_runtime(); + + assert_eq!(tables.init(), Ok(())); + + let virt_end_exclusive_page_addr: PageAddress = PageAddress::MAX; + let virt_start_page_addr: PageAddress = + virt_end_exclusive_page_addr.checked_offset(-5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + + let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + + assert_eq!( + tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), + Ok(phys_start_page_addr) + ); + + assert_eq!( + tables.try_page_attributes(virt_start_page_addr.checked_offset(-1).unwrap()), + Err("Page marked invalid") + ); + + assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); + + let virt_addr = virt_start_page_addr.into_inner() + 0x100; + let phys_addr = phys_start_page_addr.into_inner() + 0x100; + assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); + } +} diff --git a/19_kernel_heap/kernel/src/memory/mmu/types.rs b/19_kernel_heap/kernel/src/memory/mmu/types.rs new file mode 100644 index 000000000..f6ac8d598 --- /dev/null +++ b/19_kernel_heap/kernel/src/memory/mmu/types.rs @@ -0,0 +1,378 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + +use crate::{ + bsp, common, + memory::{Address, AddressType, Physical}, +}; +use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct PageAddress { + inner: Address, +} + +/// A type that describes a region of memory in quantities of pages. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// An MMIO descriptor for use in device drivers. +#[derive(Copy, Clone)] +pub struct MMIODescriptor { + start_addr: Address, + end_addr_exclusive: Address, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------ +// PageAddress +//------------------------------------------------------------------------------ +impl PageAddress { + /// The largest value that can be represented by this type. + pub const MAX: Self = PageAddress { + inner: Address::new(usize::MAX).align_down_page(), + }; + + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + } + + /// Calculates the offset from the page address. + /// + /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * + /// page_size`. + pub fn checked_offset(self, count: isize) -> Option { + if count == 0 { + return Some(self); + } + + let delta = count + .unsigned_abs() + .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; + let result = if count.is_positive() { + self.inner.as_usize().checked_add(delta)? + } else { + self.inner.as_usize().checked_sub(delta)? + }; + + Some(Self { + inner: Address::new(result), + }) + } +} + +impl From for PageAddress { + fn from(addr: usize) -> Self { + assert!( + common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), + "Input usize not page aligned" + ); + + Self { + inner: Address::new(addr), + } + } +} + +impl From> for PageAddress { + fn from(addr: Address) -> Self { + assert!(addr.is_page_aligned(), "Input Address not page aligned"); + + Self { inner: addr } + } +} + +impl Step for PageAddress { + fn steps_between(start: &Self, end: &Self) -> Option { + if start > end { + return None; + } + + // Since start <= end, do unchecked arithmetic. + Some( + (end.inner.as_usize() - start.inner.as_usize()) + >> bsp::memory::mmu::KernelGranule::SHIFT, + ) + } + + fn forward_checked(start: Self, count: usize) -> Option { + start.checked_offset(count as isize) + } + + fn backward_checked(start: Self, count: usize) -> Option { + start.checked_offset(-(count as isize)) + } +} + +//------------------------------------------------------------------------------ +// MemoryRegion +//------------------------------------------------------------------------------ +impl MemoryRegion { + /// Create an instance. + pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { + assert!(start <= end_exclusive); + + Self { + start, + end_exclusive, + } + } + + fn as_range(&self) -> Range> { + self.into_iter() + } + + /// Returns the start page address. + pub fn start_page_addr(&self) -> PageAddress { + self.start + } + + /// Returns the start address. + pub fn start_addr(&self) -> Address { + self.start.into_inner() + } + + /// Returns the exclusive end page address. + pub fn end_exclusive_page_addr(&self) -> PageAddress { + self.end_exclusive + } + + /// Returns the exclusive end page address. + pub fn end_inclusive_page_addr(&self) -> PageAddress { + self.end_exclusive.checked_offset(-1).unwrap() + } + + /// Checks if self contains an address. + pub fn contains(&self, addr: Address) -> bool { + let page_addr = PageAddress::from(addr.align_down_page()); + self.as_range().contains(&page_addr) + } + + /// Checks if there is an overlap with another memory region. + pub fn overlaps(&self, other_region: &Self) -> bool { + let self_range = self.as_range(); + + self_range.contains(&other_region.start_page_addr()) + || self_range.contains(&other_region.end_inclusive_page_addr()) + } + + /// Returns the number of pages contained in this region. + pub fn num_pages(&self) -> usize { + PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() + } + + /// Returns the size in bytes of this region. + pub fn size(&self) -> usize { + // Invariant: start <= end_exclusive, so do unchecked arithmetic. + let end_exclusive = self.end_exclusive.into_inner().as_usize(); + let start = self.start.into_inner().as_usize(); + + end_exclusive - start + } + + /// Splits the MemoryRegion like: + /// + /// -------------------------------------------------------------------------------- + /// | | | | | | | | | | | | | | | | | | | + /// -------------------------------------------------------------------------------- + /// ^ ^ ^ + /// | | | + /// left_start left_end_exclusive | + /// | + /// ^ | + /// | | + /// right_start right_end_exclusive + /// + /// Left region is returned to the caller. Right region is the new region for this struct. + pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { + let count: usize = num_pages.into(); + + let left_end_exclusive = self.start.checked_offset(count as isize); + let left_end_exclusive = match left_end_exclusive { + None => return Err("Overflow while calculating left_end_exclusive"), + Some(x) => x, + }; + + if left_end_exclusive > self.end_exclusive { + return Err("Not enough free pages"); + } + + let allocation = Self { + start: self.start, + end_exclusive: left_end_exclusive, + }; + self.start = left_end_exclusive; + + Ok(allocation) + } +} + +impl IntoIterator for MemoryRegion { + type Item = PageAddress; + type IntoIter = Range; + + fn into_iter(self) -> Self::IntoIter { + Range { + start: self.start, + end: self.end_exclusive, + } + } +} + +impl From for MemoryRegion { + fn from(desc: MMIODescriptor) -> Self { + let start = PageAddress::from(desc.start_addr.align_down_page()); + let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); + + Self { + start, + end_exclusive, + } + } +} + +//------------------------------------------------------------------------------ +// MMIODescriptor +//------------------------------------------------------------------------------ + +impl MMIODescriptor { + /// Create an instance. + pub const fn new(start_addr: Address, size: usize) -> Self { + assert!(size > 0); + let end_addr_exclusive = Address::new(start_addr.as_usize() + size); + + Self { + start_addr, + end_addr_exclusive, + } + } + + /// Return the start address. + pub const fn start_addr(&self) -> Address { + self.start_addr + } + + /// Return the exclusive end address. + pub fn end_addr_exclusive(&self) -> Address { + self.end_addr_exclusive + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::Virtual; + use test_macros::kernel_test; + + /// Sanity of [PageAddress] methods. + #[kernel_test] + fn pageaddress_type_method_sanity() { + let page_addr: PageAddress = + PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); + + assert_eq!( + page_addr.checked_offset(-2), + Some(PageAddress::::from(0)) + ); + + assert_eq!( + page_addr.checked_offset(2), + Some(PageAddress::::from( + bsp::memory::mmu::KernelGranule::SIZE * 4 + )) + ); + + assert_eq!( + PageAddress::::from(0).checked_offset(0), + Some(PageAddress::::from(0)) + ); + assert_eq!(PageAddress::::from(0).checked_offset(-1), None); + + let max_page_addr = Address::::new(usize::MAX).align_down_page(); + assert_eq!( + PageAddress::::from(max_page_addr).checked_offset(1), + None + ); + + let zero = PageAddress::::from(0); + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); + } + + /// Sanity of [MemoryRegion] methods. + #[kernel_test] + fn memoryregion_type_method_sanity() { + let zero = PageAddress::::from(0); + let zero_region = MemoryRegion::new(zero, zero); + assert_eq!(zero_region.num_pages(), 0); + assert_eq!(zero_region.size(), 0); + + let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); + let one_region = MemoryRegion::new(zero, one); + assert_eq!(one_region.num_pages(), 1); + assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); + + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + let mut three_region = MemoryRegion::new(zero, three); + assert!(three_region.contains(zero.into_inner())); + assert!(!three_region.contains(three.into_inner())); + assert!(three_region.overlaps(&one_region)); + + let allocation = three_region + .take_first_n_pages(NonZeroUsize::new(2).unwrap()) + .unwrap(); + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + + for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE + ); + } + } +} diff --git a/19_kernel_heap/kernel/src/panic_wait.rs b/19_kernel_heap/kernel/src/panic_wait.rs new file mode 100644 index 000000000..389eb2c88 --- /dev/null +++ b/19_kernel_heap/kernel/src/panic_wait.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{backtrace, cpu, exception, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + backtrace::Backtrace + ); + + _panic_exit() +} diff --git a/19_kernel_heap/kernel/src/print.rs b/19_kernel_heap/kernel/src/print.rs new file mode 100644 index 000000000..a89f8201d --- /dev/null +++ b/19_kernel_heap/kernel/src/print.rs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Debug print, with a newline. +#[macro_export] +macro_rules! debug { + ($string:expr) => ({ + if cfg!(feature = "debug_prints") { + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("<[>D {:>3}.{:06}> ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + } + }); + ($format_string:expr, $($arg:tt)*) => ({ + if cfg!(feature = "debug_prints") { + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("3}.{:06}> ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + } + }) +} diff --git a/19_kernel_heap/kernel/src/state.rs b/19_kernel_heap/kernel/src/state.rs new file mode 100644 index 000000000..6d99beedb --- /dev/null +++ b/19_kernel_heap/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff --git a/19_kernel_heap/kernel/src/symbols.rs b/19_kernel_heap/kernel/src/symbols.rs new file mode 100644 index 000000000..fdc1d084c --- /dev/null +++ b/19_kernel_heap/kernel/src/symbols.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Debug symbol support. + +use crate::memory::{Address, Virtual}; +use core::{cell::UnsafeCell, slice}; +use debug_symbol_types::Symbol; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbol from the linker script. +extern "Rust" { + static __kernel_symbols_start: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// This will be patched to the correct value by the "kernel symbols tool" after linking. This given +/// value here is just a (safe) dummy. +#[no_mangle] +static NUM_KERNEL_SYMBOLS: u64 = 0; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn kernel_symbol_section_virt_start_addr() -> Address { + Address::new(unsafe { __kernel_symbols_start.get() as usize }) +} + +fn num_kernel_symbols() -> usize { + unsafe { + // Read volatile is needed here to prevent the compiler from optimizing NUM_KERNEL_SYMBOLS + // away. + core::ptr::read_volatile(&NUM_KERNEL_SYMBOLS as *const u64) as usize + } +} + +fn kernel_symbols_slice() -> &'static [Symbol] { + let ptr = kernel_symbol_section_virt_start_addr().as_usize() as *const Symbol; + + unsafe { slice::from_raw_parts(ptr, num_kernel_symbols()) } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Retrieve the symbol corresponding to a virtual address, if any. +pub fn lookup_symbol(addr: Address) -> Option<&'static Symbol> { + kernel_symbols_slice() + .iter() + .find(|&i| i.contains(addr.as_usize())) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of symbols module. + #[kernel_test] + fn symbols_sanity() { + let first_sym = lookup_symbol(Address::new( + crate::common::is_aligned as *const usize as usize, + )) + .unwrap() + .name(); + + assert_eq!(first_sym, "libkernel::common::is_aligned"); + + let second_sym = lookup_symbol(Address::new(crate::version as *const usize as usize)) + .unwrap() + .name(); + + assert_eq!(second_sym, "libkernel::version"); + } +} diff --git a/19_kernel_heap/kernel/src/synchronization.rs b/19_kernel_heap/kernel/src/synchronization.rs new file mode 100644 index 000000000..5740b63e5 --- /dev/null +++ b/19_kernel_heap/kernel/src/synchronization.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use crate::{exception, state}; + +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } +} diff --git a/19_kernel_heap/kernel/src/time.rs b/19_kernel_heap/kernel/src/time.rs new file mode 100644 index 000000000..a9d501204 --- /dev/null +++ b/19_kernel_heap/kernel/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff --git a/19_kernel_heap/kernel/tests/00_console_sanity.rb b/19_kernel_heap/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/19_kernel_heap/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/19_kernel_heap/kernel/tests/00_console_sanity.rs b/19_kernel_heap/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..682ea9b8a --- /dev/null +++ b/19_kernel_heap/kernel/tests/00_console_sanity.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, memory, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/19_kernel_heap/kernel/tests/01_timer_sanity.rs b/19_kernel_heap/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..1581a02e0 --- /dev/null +++ b/19_kernel_heap/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, memory, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/19_kernel_heap/kernel/tests/02_exception_sync_page_fault.rs b/19_kernel_heap/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..09d177981 --- /dev/null +++ b/19_kernel_heap/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + info!("Writing to bottom of address space to address 1 GiB..."); + let big_addr: u64 = 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/19_kernel_heap/kernel/tests/03_exception_restore_sanity.rb b/19_kernel_heap/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/19_kernel_heap/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/19_kernel_heap/kernel/tests/03_exception_restore_sanity.rs b/19_kernel_heap/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..1a3029112 --- /dev/null +++ b/19_kernel_heap/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/19_kernel_heap/kernel/tests/04_exception_irq_sanity.rs b/19_kernel_heap/kernel/tests/04_exception_irq_sanity.rs new file mode 100644 index 000000000..fcace8979 --- /dev/null +++ b/19_kernel_heap/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception, memory}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + memory::init(); + bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} diff --git a/19_kernel_heap/kernel/tests/05_backtrace_sanity.rb b/19_kernel_heap/kernel/tests/05_backtrace_sanity.rb new file mode 100644 index 000000000..243e2fc86 --- /dev/null +++ b/19_kernel_heap/kernel/tests/05_backtrace_sanity.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that panic produces a backtrace. +class PanicBacktraceTest < SubtestBase + def name + 'Panic produces backtrace' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Kernel panic!') + expect_or_raise(qemu_out, 'Backtrace:') + end +end + +# Verify backtrace correctness. +class BacktraceCorrectnessTest < SubtestBase + def name + 'Backtrace is correct' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '| core::panicking::panic') + expect_or_raise(qemu_out, '| _05_backtrace_sanity::nested') + expect_or_raise(qemu_out, '| kernel_init') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [PanicBacktraceTest.new, BacktraceCorrectnessTest.new] +end diff --git a/19_kernel_heap/kernel/tests/05_backtrace_sanity.rs b/19_kernel_heap/kernel/tests/05_backtrace_sanity.rs new file mode 100644 index 000000000..66fd0a3e7 --- /dev/null +++ b/19_kernel_heap/kernel/tests/05_backtrace_sanity.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid frame pointer. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested() { + panic!() +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/19_kernel_heap/kernel/tests/06_backtrace_invalid_frame.rb b/19_kernel_heap/kernel/tests/06_backtrace_invalid_frame.rb new file mode 100644 index 000000000..806954682 --- /dev/null +++ b/19_kernel_heap/kernel/tests/06_backtrace_invalid_frame.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Test detection of invalid frame pointers. +class InvalidFramePointerTest < SubtestBase + def name + 'Detect invalid frame pointer' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, + /Encountered invalid frame pointer \(.*\) during backtrace/) + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [InvalidFramePointerTest.new] +end diff --git a/19_kernel_heap/kernel/tests/06_backtrace_invalid_frame.rs b/19_kernel_heap/kernel/tests/06_backtrace_invalid_frame.rs new file mode 100644 index 000000000..38411af69 --- /dev/null +++ b/19_kernel_heap/kernel/tests/06_backtrace_invalid_frame.rs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid frame pointer. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{backtrace, bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested() { + unsafe { backtrace::corrupt_previous_frame_addr() }; + + panic!() +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/19_kernel_heap/kernel/tests/07_backtrace_invalid_link.rb b/19_kernel_heap/kernel/tests/07_backtrace_invalid_link.rb new file mode 100644 index 000000000..6b6f04132 --- /dev/null +++ b/19_kernel_heap/kernel/tests/07_backtrace_invalid_link.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Test detection of invalid link. +class InvalidLinkTest < SubtestBase + def name + 'Detect invalid link' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, /Link address \(.*\) is not contained in kernel .text section/) + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [InvalidLinkTest.new] +end diff --git a/19_kernel_heap/kernel/tests/07_backtrace_invalid_link.rs b/19_kernel_heap/kernel/tests/07_backtrace_invalid_link.rs new file mode 100644 index 000000000..6e0873dd1 --- /dev/null +++ b/19_kernel_heap/kernel/tests/07_backtrace_invalid_link.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid link. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{backtrace, bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested_2() -> &'static str { + unsafe { backtrace::corrupt_link() }; + libkernel::println!("{}", libkernel::backtrace::Backtrace); + "foo" +} + +#[inline(never)] +fn nested_1() { + libkernel::println!("{}", nested_2()) +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested_1(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/19_kernel_heap/kernel/tests/boot_test_string.rb b/19_kernel_heap/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..f778b3d8c --- /dev/null +++ b/19_kernel_heap/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Echoing input now' diff --git a/19_kernel_heap/kernel/tests/panic_exit_success/mod.rs b/19_kernel_heap/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/19_kernel_heap/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/19_kernel_heap/kernel/tests/panic_wait_forever/mod.rs b/19_kernel_heap/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/19_kernel_heap/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/19_kernel_heap/kernel_symbols.mk b/19_kernel_heap/kernel_symbols.mk new file mode 100644 index 000000000..d38b7785a --- /dev/null +++ b/19_kernel_heap/kernel_symbols.mk @@ -0,0 +1,117 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/format.mk +include ../common/docker.mk + +##-------------------------------------------------------------------------------------------------- +## Check for input variables that need be exported by the calling Makefile +##-------------------------------------------------------------------------------------------------- +ifndef KERNEL_SYMBOLS_TOOL_PATH +$(error KERNEL_SYMBOLS_TOOL_PATH is not set) +endif + +ifndef TARGET +$(error TARGET is not set) +endif + +ifndef KERNEL_SYMBOLS_INPUT_ELF +$(error KERNEL_SYMBOLS_INPUT_ELF is not set) +endif + +ifndef KERNEL_SYMBOLS_OUTPUT_ELF +$(error KERNEL_SYMBOLS_OUTPUT_ELF is not set) +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_SYMBOLS_MANIFEST = kernel_symbols/Cargo.toml +KERNEL_SYMBOLS_LINKER_SCRIPT = kernel_symbols/kernel_symbols.ld + +KERNEL_SYMBOLS_RS = $(KERNEL_SYMBOLS_INPUT_ELF)_symbols.rs +KERNEL_SYMBOLS_DEMANGLED_RS = $(shell pwd)/$(KERNEL_SYMBOLS_INPUT_ELF)_symbols_demangled.rs + +KERNEL_SYMBOLS_ELF = target/$(TARGET)/release/kernel_symbols +KERNEL_SYMBOLS_STRIPPED = target/$(TARGET)/release/kernel_symbols_stripped + +# Export for build.rs of kernel_symbols crate. +export KERNEL_SYMBOLS_DEMANGLED_RS + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +GET_SYMBOLS_SECTION_VIRT_ADDR = $(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) \ + --get_symbols_section_virt_addr $(KERNEL_SYMBOLS_OUTPUT_ELF) + +RUSTFLAGS = -C link-arg=--script=$(KERNEL_SYMBOLS_LINKER_SCRIPT) \ + -C link-arg=--section-start=.rodata=$$($(GET_SYMBOLS_SECTION_VIRT_ADDR)) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +COMPILER_ARGS = --target=$(TARGET) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_SYMBOLS_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_SYMBOLS_TOOL = ruby $(KERNEL_SYMBOLS_TOOL_PATH)/main.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all symbols measure_time_start measure_time_finish + +all: measure_time_start symbols measure_time_finish + +symbols: + @cp $(KERNEL_SYMBOLS_INPUT_ELF) $(KERNEL_SYMBOLS_OUTPUT_ELF) + + @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --gen_symbols $(KERNEL_SYMBOLS_OUTPUT_ELF) \ + $(KERNEL_SYMBOLS_RS) + + $(call color_progress_prefix, "Demangling") + @echo Symbol names + @cat $(KERNEL_SYMBOLS_RS) | rustfilt > $(KERNEL_SYMBOLS_DEMANGLED_RS) + + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + + $(call color_progress_prefix, "Stripping") + @echo Symbols ELF file + @$(OBJCOPY_CMD) $(KERNEL_SYMBOLS_ELF) $(KERNEL_SYMBOLS_STRIPPED) + + @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --patch_data $(KERNEL_SYMBOLS_OUTPUT_ELF) \ + $(KERNEL_SYMBOLS_STRIPPED) + +# Note: The following is the only _trivial_ way I could think of that works out of the box on both +# Linux and macOS. Since macOS does not have the %N nanosecond format string option, the +# resolution is restricted to whole seconds. +measure_time_start: + @date +%s > /tmp/kernel_symbols_start.date + +measure_time_finish: + @date +%s > /tmp/kernel_symbols_end.date + + $(call color_progress_prefix, "Finished") + @echo "in $$((`cat /tmp/kernel_symbols_end.date` - `cat /tmp/kernel_symbols_start.date`)).0s" + + @rm /tmp/kernel_symbols_end.date /tmp/kernel_symbols_start.date diff --git a/19_kernel_heap/kernel_symbols/Cargo.lock b/19_kernel_heap/kernel_symbols/Cargo.lock new file mode 100644 index 000000000..70b7fa662 --- /dev/null +++ b/19_kernel_heap/kernel_symbols/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "debug-symbol-types" +version = "0.1.0" + +[[package]] +name = "kernel_symbols" +version = "0.1.0" +dependencies = [ + "debug-symbol-types", +] diff --git a/19_kernel_heap/kernel_symbols/Cargo.toml b/19_kernel_heap/kernel_symbols/Cargo.toml new file mode 100644 index 000000000..3407aa7e1 --- /dev/null +++ b/19_kernel_heap/kernel_symbols/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "kernel_symbols" +version = "0.1.0" +edition = "2021" + +[features] +default = [] +generated_symbols_available = [] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +debug-symbol-types = { path = "../libraries/debug-symbol-types" } diff --git a/19_kernel_heap/kernel_symbols/build.rs b/19_kernel_heap/kernel_symbols/build.rs new file mode 100644 index 000000000..5062df444 --- /dev/null +++ b/19_kernel_heap/kernel_symbols/build.rs @@ -0,0 +1,14 @@ +use std::{env, path::Path}; + +fn main() { + if let Ok(path) = env::var("KERNEL_SYMBOLS_DEMANGLED_RS") { + if Path::new(&path).exists() { + println!("cargo:rustc-cfg=feature=\"generated_symbols_available\"") + } + } + + println!( + "cargo:rerun-if-changed={}", + Path::new("kernel_symbols.ld").display() + ); +} diff --git a/19_kernel_heap/kernel_symbols/kernel_symbols.ld b/19_kernel_heap/kernel_symbols/kernel_symbols.ld new file mode 100644 index 000000000..0625f0086 --- /dev/null +++ b/19_kernel_heap/kernel_symbols/kernel_symbols.ld @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2022 Andre Richter + */ + +SECTIONS +{ + .rodata : { + ASSERT(. > 0xffffffff00000000, "Expected higher half address") + + KEEP(*(.rodata.symbol_desc*)) + . = ALIGN(8); + *(.rodata*) + } +} diff --git a/19_kernel_heap/kernel_symbols/src/main.rs b/19_kernel_heap/kernel_symbols/src/main.rs new file mode 100644 index 000000000..38ce18f8f --- /dev/null +++ b/19_kernel_heap/kernel_symbols/src/main.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Generation of kernel symbols. + +#![no_std] +#![no_main] + +#[cfg(feature = "generated_symbols_available")] +include!(env!("KERNEL_SYMBOLS_DEMANGLED_RS")); + +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unimplemented!() +} diff --git a/19_kernel_heap/libraries/debug-symbol-types/Cargo.toml b/19_kernel_heap/libraries/debug-symbol-types/Cargo.toml new file mode 100644 index 000000000..e5b1fd1f5 --- /dev/null +++ b/19_kernel_heap/libraries/debug-symbol-types/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "debug-symbol-types" +version = "0.1.0" +edition = "2021" diff --git a/19_kernel_heap/libraries/debug-symbol-types/src/lib.rs b/19_kernel_heap/libraries/debug-symbol-types/src/lib.rs new file mode 100644 index 000000000..81c897bfa --- /dev/null +++ b/19_kernel_heap/libraries/debug-symbol-types/src/lib.rs @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Types for implementing debug symbol support. + +#![no_std] + +use core::ops::Range; + +/// A symbol containing a size. +#[repr(C)] +#[derive(Clone)] +pub struct Symbol { + addr_range: Range, + name: &'static str, +} + +impl Symbol { + /// Create an instance. + pub const fn new(start: usize, size: usize, name: &'static str) -> Symbol { + Symbol { + addr_range: Range { + start, + end: start + size, + }, + name, + } + } + + /// Returns true if addr is contained in the range. + pub fn contains(&self, addr: usize) -> bool { + self.addr_range.contains(&addr) + } + + /// Returns the symbol's name. + pub fn name(&self) -> &'static str { + self.name + } + + /// Returns the symbol's size. + pub fn size(&self) -> usize { + self.addr_range.end - self.addr_range.start + } +} diff --git a/19_kernel_heap/libraries/test-macros/Cargo.toml b/19_kernel_heap/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/19_kernel_heap/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/19_kernel_heap/libraries/test-macros/src/lib.rs b/19_kernel_heap/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/19_kernel_heap/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/19_kernel_heap/libraries/test-types/Cargo.toml b/19_kernel_heap/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/19_kernel_heap/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/19_kernel_heap/libraries/test-types/src/lib.rs b/19_kernel_heap/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/19_kernel_heap/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/19_kernel_heap/tools/kernel_symbols_tool/cmds.rb b/19_kernel_heap/tools/kernel_symbols_tool/cmds.rb new file mode 100644 index 000000000..c43acb24c --- /dev/null +++ b/19_kernel_heap/tools/kernel_symbols_tool/cmds.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +def generate_symbols(kernel_elf, output_file) + File.open(output_file, 'w') do |file| + header = <<~HEREDOC + use debug_symbol_types::Symbol; + + # [no_mangle] + # [link_section = ".rodata.symbol_desc"] + static KERNEL_SYMBOLS: [Symbol; #{kernel_elf.num_symbols}] = [ + HEREDOC + + file.write(header) + kernel_elf.symbols.each do |sym| + value = sym.header.st_value + size = sym.header.st_size + name = sym.name + + file.write(" Symbol::new(#{value}, #{size}, \"#{name}\"),\n") + end + file.write("];\n") + end +end + +def get_symbols_section_virt_addr(kernel_elf) + kernel_elf.kernel_symbols_section_virt_addr +end + +def patch_symbol_data(kernel_elf, symbols_blob_path) + symbols_blob = File.binread(symbols_blob_path) + + raise if symbols_blob.size > kernel_elf.kernel_symbols_section_size + + File.binwrite(kernel_elf.path, File.binread(symbols_blob_path), + kernel_elf.kernel_symbols_section_offset_in_file) +end + +def patch_num_symbols(kernel_elf) + num_packed = [kernel_elf.num_symbols].pack('Q<*') # "Q" == uint64_t, "<" == little endian + File.binwrite(kernel_elf.path, num_packed, kernel_elf.num_kernel_symbols_offset_in_file) +end diff --git a/19_kernel_heap/tools/kernel_symbols_tool/kernel_elf.rb b/19_kernel_heap/tools/kernel_symbols_tool/kernel_elf.rb new file mode 100644 index 000000000..32b5460aa --- /dev/null +++ b/19_kernel_heap/tools/kernel_symbols_tool/kernel_elf.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + attr_reader :path + + def initialize(kernel_elf_path, kernel_symbols_section, num_kernel_symbols) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + + @path = kernel_elf_path + fetch_values(kernel_symbols_section, num_kernel_symbols) + end + + private + + def fetch_values(kernel_symbols_section, num_kernel_symbols) + sym = @symtab_section.symbol_by_name(num_kernel_symbols) + raise "Symbol \"#{num_kernel_symbols}\" not found" if sym.nil? + + @num_kernel_symbols = sym + + section = @elf.section_by_name(kernel_symbols_section) + raise "Section \"#{kernel_symbols_section}\" not found" if section.nil? + + @kernel_symbols_section = section + end + + def num_kernel_symbols_virt_addr + @num_kernel_symbols.header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + public + + def symbols + non_zero_symbols = @symtab_section.symbols.reject { |sym| sym.header.st_size.zero? } + non_zero_symbols.sort_by { |sym| sym.header.st_value } + end + + def num_symbols + symbols.size + end + + def kernel_symbols_section_virt_addr + @kernel_symbols_section.header.sh_addr.to_i + end + + def kernel_symbols_section_size + @kernel_symbols_section.header.sh_size.to_i + end + + def kernel_symbols_section_offset_in_file + virt_addr_to_file_offset(kernel_symbols_section_virt_addr) + end + + def num_kernel_symbols_offset_in_file + virt_addr_to_file_offset(num_kernel_symbols_virt_addr) + end +end diff --git a/19_kernel_heap/tools/kernel_symbols_tool/main.rb b/19_kernel_heap/tools/kernel_symbols_tool/main.rb new file mode 100755 index 000000000..899f96464 --- /dev/null +++ b/19_kernel_heap/tools/kernel_symbols_tool/main.rb @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'kernel_elf' +require_relative 'cmds' + +KERNEL_SYMBOLS_SECTION = '.kernel_symbols' +NUM_KERNEL_SYMBOLS = 'NUM_KERNEL_SYMBOLS' + +cmd = ARGV[0] + +kernel_elf_path = ARGV[1] +kernel_elf = KernelELF.new(kernel_elf_path, KERNEL_SYMBOLS_SECTION, NUM_KERNEL_SYMBOLS) + +case cmd +when '--gen_symbols' + output_file = ARGV[2] + + print 'Generating'.rjust(12).green.bold + puts ' Symbols source file' + + generate_symbols(kernel_elf, output_file) +when '--get_symbols_section_virt_addr' + addr = get_symbols_section_virt_addr(kernel_elf) + + puts "0x#{addr.to_s(16)}" +when '--patch_data' + symbols_blob_path = ARGV[2] + num_symbols = kernel_elf.num_symbols + + print 'Patching'.rjust(12).green.bold + puts " Symbols blob and number of symbols (#{num_symbols}) into ELF" + + patch_symbol_data(kernel_elf, symbols_blob_path) + patch_num_symbols(kernel_elf) +else + raise +end diff --git a/19_kernel_heap/tools/translation_table_tool/arch.rb b/19_kernel_heap/tools/translation_table_tool/arch.rb new file mode 100644 index 000000000..053cac194 --- /dev/null +++ b/19_kernel_heap/tools/translation_table_tool/arch.rb @@ -0,0 +1,314 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Bitfield manipulation. +class BitField + def initialize + @value = 0 + end + + def self.attr_bitfield(name, offset, num_bits) + define_method("#{name}=") do |bits| + mask = (2**num_bits) - 1 + + raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? + + # Clear bitfield + @value &= ~(mask << offset) + + # Set it + @value |= (bits << offset) + end + end + + def to_i + @value + end + + def size_in_byte + 8 + end +end + +# An array class that knows its memory location. +class CArray < Array + attr_reader :phys_start_addr + + def initialize(phys_start_addr, size, &block) + @phys_start_addr = phys_start_addr + + super(size, &block) + end + + def size_in_byte + inject(0) { |sum, n| sum + n.size_in_byte } + end +end + +#--------------------------------------------------------------------------------------------------- +# Arch:: +#--------------------------------------------------------------------------------------------------- +module Arch +#--------------------------------------------------------------------------------------------------- +# Arch::ARMv8 +#--------------------------------------------------------------------------------------------------- +module ARMv8 +# ARMv8 Table Descriptor. +class Stage1TableDescriptor < BitField + module NextLevelTableAddr + OFFSET = 16 + NUMBITS = 32 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + BLOCK = 0 + TABLE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def next_level_table_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__next_level_table_addr = addr + end + + private :__next_level_table_addr= +end + +# ARMv8 level 3 page descriptor. +class Stage1PageDescriptor < BitField + module UXN + OFFSET = 54 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module PXN + OFFSET = 53 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module OutputAddr + OFFSET = 16 + NUMBITS = 32 + end + + module AF + OFFSET = 10 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module SH + OFFSET = 8 + NUMBITS = 2 + + INNER_SHAREABLE = 0b11 + end + + module AP + OFFSET = 6 + NUMBITS = 2 + + RW_EL1 = 0b00 + RO_EL1 = 0b10 + end + + module AttrIndx + OFFSET = 2 + NUMBITS = 3 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + RESERVED_INVALID = 0 + PAGE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) + attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) + attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) + attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) + attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) + attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) + attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def output_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__output_addr = addr + end + + private :__output_addr= +end + +# Translation table representing the structure defined in translation_table.rs. +class TranslationTable + module MAIR + NORMAL = 1 + end + + def initialize + do_sanity_checks + + num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT + + @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) + + @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte + @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) + + populate_lvl2_entries + end + + def map_at(virt_region, phys_region, attributes) + return if virt_region.empty? + + raise if virt_region.size != phys_region.size + raise if phys_region.last > BSP.phys_addr_space_end_page + + virt_region.zip(phys_region).each do |virt_page, phys_page| + desc = page_descriptor_from(virt_page) + set_lvl3_entry(desc, phys_page, attributes) + end + end + + def to_binary + data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) + data.pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr_binary + [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr + @lvl2_phys_start_addr + end + + private + + def do_sanity_checks + raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE + raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? + end + + def new_lvl3(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + temp = CArray.new(start_addr, 8192) do + Stage1PageDescriptor.new + end + start_addr += temp.size_in_byte + + temp + end + end + + def new_lvl2(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + Stage1TableDescriptor.new + end + end + + def populate_lvl2_entries + @lvl2.each_with_index do |descriptor, i| + descriptor.next_level_table_addr = @lvl3[i].phys_start_addr + descriptor.type = Stage1TableDescriptor::Type::TABLE + descriptor.valid = Stage1TableDescriptor::Valid::TRUE + end + end + + def lvl2_lvl3_index_from(addr) + addr -= BSP.kernel_virt_start_addr + + lvl2_index = addr >> Granule512MiB::SHIFT + lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT + + raise unless lvl2_index < @lvl2.size + + [lvl2_index, lvl3_index] + end + + def page_descriptor_from(virt_addr) + lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) + + @lvl3[lvl2_index][lvl3_index] + end + + # rubocop:disable Metrics/MethodLength + def set_attributes(desc, attributes) + case attributes.mem_attributes + when :CacheableDRAM + desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE + desc.attr_indx = MAIR::NORMAL + else + raise 'Invalid input' + end + + desc.ap = case attributes.acc_perms + when :ReadOnly + Stage1PageDescriptor::AP::RO_EL1 + when :ReadWrite + Stage1PageDescriptor::AP::RW_EL1 + else + raise 'Invalid input' + + end + + desc.pxn = if attributes.execute_never + Stage1PageDescriptor::PXN::TRUE + else + Stage1PageDescriptor::PXN::FALSE + end + + desc.uxn = Stage1PageDescriptor::UXN::TRUE + end + # rubocop:enable Metrics/MethodLength + + def set_lvl3_entry(desc, output_addr, attributes) + desc.output_addr = output_addr + desc.af = Stage1PageDescriptor::AF::TRUE + desc.type = Stage1PageDescriptor::Type::PAGE + desc.valid = Stage1PageDescriptor::Valid::TRUE + + set_attributes(desc, attributes) + end +end +end +end diff --git a/19_kernel_heap/tools/translation_table_tool/bsp.rb b/19_kernel_heap/tools/translation_table_tool/bsp.rb new file mode 100644 index 000000000..5887d7745 --- /dev/null +++ b/19_kernel_heap/tools/translation_table_tool/bsp.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Raspberry Pi 3 + 4 +class RaspberryPi + attr_reader :kernel_granule, :kernel_virt_addr_space_size, :kernel_virt_start_addr + + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + + def initialize + @kernel_granule = Granule64KiB + + @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') + @kernel_virt_start_addr = KERNEL_ELF.symbol_value('__kernel_virt_start_addr') + + @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') + @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( + 'PHYS_KERNEL_TABLES_BASE_ADDR' + ) + end + + def phys_addr_of_kernel_tables + KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) + end + + def kernel_tables_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) + end + + def phys_kernel_tables_base_addr_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) + end + + def phys_addr_space_end_page + x = MEMORY_SRC.grep(/pub const END/) + x = case BSP_TYPE + when :rpi3 + x[0] + when :rpi4 + x[1] + else + raise + end + + # Extract the hex literal with underscores like 0x0123_abcd. + x = x.scan(/0x[\h_]*/)[0] + + # Further remove x and _ and convert to int. + x.scan(/\h+/).join.to_i(16) + end +end diff --git a/19_kernel_heap/tools/translation_table_tool/generic.rb b/19_kernel_heap/tools/translation_table_tool/generic.rb new file mode 100644 index 000000000..941e2226f --- /dev/null +++ b/19_kernel_heap/tools/translation_table_tool/generic.rb @@ -0,0 +1,189 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +module Granule64KiB + SIZE = 64 * 1024 + SHIFT = Math.log2(SIZE).to_i +end + +module Granule512MiB + SIZE = 512 * 1024 * 1024 + SHIFT = Math.log2(SIZE).to_i + MASK = SIZE - 1 +end + +# Monkey-patch Integer with some helper functions. +class Integer + def power_of_two? + self[0].zero? + end + + def aligned?(alignment) + raise unless alignment.power_of_two? + + (self & (alignment - 1)).zero? + end + + def align_up(alignment) + raise unless alignment.power_of_two? + + (self + alignment - 1) & ~(alignment - 1) + end + + def to_hex_underscore(with_leading_zeros: false) + fmt = with_leading_zeros ? '%016x' : '%x' + value = format(fmt, self).to_s.reverse.scan(/.{4}|.+/).join('_').reverse + + format('0x%s', value) + end +end + +# An array where each value is the start address of a Page. +class MemoryRegion < Array + def initialize(start_addr, size, granule_size) + raise unless start_addr.aligned?(granule_size) + raise unless size.positive? + raise unless (size % granule_size).zero? + + num_pages = size / granule_size + super(num_pages) do |i| + (i * granule_size) + start_addr + end + end +end + +# Collection of memory attributes. +class AttributeFields + attr_reader :mem_attributes, :acc_perms, :execute_never + + def initialize(mem_attributes, acc_perms, execute_never) + @mem_attributes = mem_attributes + @acc_perms = acc_perms + @execute_never = execute_never + end + + def to_s + x = case @mem_attributes + when :CacheableDRAM + 'C' + else + '?' + end + + y = case @acc_perms + when :ReadWrite + 'RW' + when :ReadOnly + 'RO' + else + '??' + end + + z = @execute_never ? 'XN' : 'X ' + + "#{x} #{y} #{z}" + end +end + +# A container that describes a virt-to-phys region mapping. +class MappingDescriptor + @max_section_name_length = 'Sections'.length + + class << self + attr_accessor :max_section_name_length + + def update_max_section_name_length(length) + @max_section_name_length = [@max_section_name_length, length].max + end + end + + attr_reader :name, :virt_region, :phys_region, :attributes + + def initialize(name, virt_region, phys_region, attributes) + @name = name + @virt_region = virt_region + @phys_region = phys_region + @attributes = attributes + end + + def size_human_readable(size) + if size >= (1024 * 1024) + "#{(size / (1024 * 1024)).to_s.rjust(3)} MiB" + elsif size >= 1024 + "#{(size / 1024).to_s.rjust(3)} KiB" + else + raise + end + end + + def to_s + name = @name.ljust(self.class.max_section_name_length) + virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) + phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) + size = size_human_readable(@virt_region.size * 65_536) + + "#{name} | #{virt_start} | #{phys_start} | #{size} | #{@attributes}" + end + + def self.print_divider + print ' ' + print '-' * max_section_name_length + puts '--------------------------------------------------------------------' + end + + def self.print_header + print_divider + print ' ' + print 'Sections'.center(max_section_name_length) + print ' ' + print 'Virt Start Addr'.center(21) + print ' ' + print 'Phys Start Addr'.center(21) + print ' ' + print 'Size'.center(7) + print ' ' + print 'Attr'.center(7) + puts + print_divider + end +end + +def kernel_map_binary + mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors + + # Generate_mapping_descriptors updates the header being printed with this call. So it must come + # afterwards. + MappingDescriptor.print_header + + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' + puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end + + MappingDescriptor.print_divider +end + +def kernel_patch_tables(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel table struct at ELF file offset ' + puts BSP.kernel_tables_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.to_binary, BSP.kernel_tables_offset_in_file) +end + +def kernel_patch_base_addr(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel tables physical base address start argument to value ' + print TRANSLATION_TABLES.phys_tables_base_addr.to_hex_underscore + print ' at ELF file offset ' + puts BSP.phys_kernel_tables_base_addr_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.phys_tables_base_addr_binary, + BSP.phys_kernel_tables_base_addr_offset_in_file) +end diff --git a/19_kernel_heap/tools/translation_table_tool/kernel_elf.rb b/19_kernel_heap/tools/translation_table_tool/kernel_elf.rb new file mode 100644 index 000000000..5ba78d9df --- /dev/null +++ b/19_kernel_heap/tools/translation_table_tool/kernel_elf.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + SECTION_FLAG_ALLOC = 2 + + def initialize(kernel_elf_path) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + end + + def machine + @elf.machine.to_sym + end + + def symbol_value(symbol_name) + @symtab_section.symbol_by_name(symbol_name).header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_to_phys(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + translation_offset = segment.header.p_vaddr - segment.header.p_paddr + + virt_addr - translation_offset + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + def sections_in_segment(segment) + head = segment.mem_head + tail = segment.mem_tail + + sections = @elf.each_sections.select do |section| + file_offset = section.header.sh_addr + flags = section.header.sh_flags + + file_offset >= head && file_offset < tail && (flags & SECTION_FLAG_ALLOC != 0) + end + + sections.map(&:name).join(' ') + end + + def select_load_segments + @elf.each_segments.select do |segment| + segment.instance_of?(ELFTools::Segments::LoadSegment) + end + end + + def segment_get_acc_perms(segment) + if segment.readable? && segment.writable? + :ReadWrite + elsif segment.readable? + :ReadOnly + else + :Invalid + end + end + + def update_max_section_name_length(descriptors) + MappingDescriptor.update_max_section_name_length(descriptors.map { |i| i.name.size }.max) + end + + def generate_mapping_descriptors + descriptors = select_load_segments.map do |segment| + # Assume each segment is page aligned. + size = segment.mem_size.align_up(BSP.kernel_granule::SIZE) + virt_start_addr = segment.header.p_vaddr + phys_start_addr = segment.header.p_paddr + acc_perms = segment_get_acc_perms(segment) + execute_never = !segment.executable? + section_names = sections_in_segment(segment) + + virt_region = MemoryRegion.new(virt_start_addr, size, BSP.kernel_granule::SIZE) + phys_region = MemoryRegion.new(phys_start_addr, size, BSP.kernel_granule::SIZE) + attributes = AttributeFields.new(:CacheableDRAM, acc_perms, execute_never) + + MappingDescriptor.new(section_names, virt_region, phys_region, attributes) + end + + update_max_section_name_length(descriptors) + descriptors + end +end diff --git a/19_kernel_heap/tools/translation_table_tool/main.rb b/19_kernel_heap/tools/translation_table_tool/main.rb new file mode 100755 index 000000000..22ab24fd5 --- /dev/null +++ b/19_kernel_heap/tools/translation_table_tool/main.rb @@ -0,0 +1,46 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'generic' +require_relative 'kernel_elf' +require_relative 'bsp' +require_relative 'arch' + +BSP_TYPE = ARGV[0].to_sym +kernel_elf_path = ARGV[1] + +start = Time.now + +KERNEL_ELF = KernelELF.new(kernel_elf_path) + +BSP = case BSP_TYPE + when :rpi3, :rpi4 + RaspberryPi.new + else + raise + end + +TRANSLATION_TABLES = case KERNEL_ELF.machine + when :AArch64 + Arch::ARMv8::TranslationTable.new + else + raise + end + +kernel_map_binary +kernel_patch_tables(kernel_elf_path) +kernel_patch_base_addr(kernel_elf_path) + +elapsed = Time.now - start + +print 'Finished'.rjust(12).green.bold +puts " in #{elapsed.round(2)}s" diff --git a/20_timer_callbacks/.cargo/config.toml b/20_timer_callbacks/.cargo/config.toml new file mode 100644 index 000000000..e34764853 --- /dev/null +++ b/20_timer_callbacks/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.'cfg(target_os = "none")'] +runner = "target/kernel_test_runner.sh" diff --git a/20_timer_callbacks/.vscode/settings.json b/20_timer_callbacks/.vscode/settings.json new file mode 100644 index 000000000..9ef30cd06 --- /dev/null +++ b/20_timer_callbacks/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--lib", "--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false +} diff --git a/20_timer_callbacks/Cargo.lock b/20_timer_callbacks/Cargo.lock new file mode 100644 index 000000000..754ed74db --- /dev/null +++ b/20_timer_callbacks/Cargo.lock @@ -0,0 +1,103 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" +dependencies = [ + "tock-registers", +] + +[[package]] +name = "debug-symbol-types" +version = "0.1.0" + +[[package]] +name = "kernel_symbols" +version = "0.1.0" +dependencies = [ + "debug-symbol-types", +] + +[[package]] +name = "linked_list_allocator" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e322f259d225fbae43a1b053b2dc6a5968a6bdf8b205f5de684dab485b95030e" + +[[package]] +name = "mingo" +version = "0.20.0" +dependencies = [ + "aarch64-cpu", + "debug-symbol-types", + "linked_list_allocator", + "qemu-exit", + "test-macros", + "test-types", + "tock-registers", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu-exit" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test-macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "test-types", +] + +[[package]] +name = "test-types" +version = "0.1.0" + +[[package]] +name = "tock-registers" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/20_timer_callbacks/Cargo.toml b/20_timer_callbacks/Cargo.toml new file mode 100644 index 000000000..38eeb1165 --- /dev/null +++ b/20_timer_callbacks/Cargo.toml @@ -0,0 +1,11 @@ +[workspace] + +members = [ + "libraries/*", + "kernel", + "kernel_symbols" +] + +[profile.release] +lto = true +debug = true diff --git a/20_timer_callbacks/Makefile b/20_timer_callbacks/Makefile new file mode 100644 index 000000000..f9704a44c --- /dev/null +++ b/20_timer_callbacks/Makefile @@ -0,0 +1,393 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. +BSP ?= rpi3 + +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + +# Optional debug prints. +ifdef DEBUG_PRINTS + FEATURES = --features debug_prints +endif + +# Optional integration test name. +ifdef TEST + TEST_ARG = --test $(TEST) +else + TEST_ARG = --test '*' +endif + + + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + +ifeq ($(BSP),rpi3) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 -C force-frame-pointers +else ifeq ($(BSP),rpi4) + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 -C force-frame-pointers +endif + +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = kernel/Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP)_$(DEBUG_PRINTS).build_config + +KERNEL_ELF_RAW = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_RAW_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Translation tables +##------------------------------------------------------------------------------ +TT_TOOL_PATH = tools/translation_table_tool + +KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables +KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) + +##------------------------------------------------------------------------------ +## Kernel symbols +##------------------------------------------------------------------------------ +export KERNEL_SYMBOLS_TOOL_PATH = tools/kernel_symbols_tool + +KERNEL_ELF_TTABLES_SYMS = target/$(TARGET)/release/kernel+ttables+symbols + +# Unlike with KERNEL_ELF_RAW, we are not relying on dep-info here. One of the reasons being that the +# name of the generated symbols file varies between runs, which can cause confusion. +KERNEL_ELF_TTABLES_SYMS_DEPS = $(KERNEL_ELF_TTABLES) \ + $(wildcard kernel_symbols/*) \ + $(wildcard $(KERNEL_SYMBOLS_TOOL_PATH)/*) + +export TARGET +export KERNEL_SYMBOLS_INPUT_ELF = $(KERNEL_ELF_TTABLES) +export KERNEL_SYMBOLS_OUTPUT_ELF = $(KERNEL_ELF_TTABLES_SYMS) + +KERNEL_ELF = $(KERNEL_ELF_TTABLES_SYMS) + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES += --features bsp_$(BSP) +COMPILER_ARGS = --target=$(TARGET) \ + $(FEATURES) \ + --release + +# build-std can be skipped for helper commands that do not rely on correct stack frames and other +# custom compiler options. This results in a huge speedup. +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) -Z build-std=core,alloc --manifest-path $(KERNEL_MANIFEST) +DOC_CMD = cargo doc $(COMPILER_ARGS) +CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) -Z build-std=core,alloc --manifest-path $(KERNEL_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot +DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check + +all: $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Precompute the kernel translation tables and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) + $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") + @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) + +##------------------------------------------------------------------------------ +## Generate kernel symbols and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES_SYMS): $(KERNEL_ELF_TTABLES_SYMS_DEPS) + $(call color_header, "Generating kernel symbols and patching kernel ELF") + @$(MAKE) --no-print-directory -f kernel_symbols.mk + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ +$(KERNEL_BIN): $(KERNEL_ELF_TTABLES_SYMS) + $(call color_header, "Generating stripped binary") + @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES_SYMS) $(KERNEL_BIN) + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ +doc: clean + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +qemu: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +endif + +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ +clippy: + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) + +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ +clean: + rm -rf target $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ +readelf: $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) + +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ +objdump: $(KERNEL_ELF) + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ +nm: $(KERNEL_ELF) + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb-opt0: RUSTC_MISC_ARGS += -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot test_unit test_integration + +test_unit test_integration: FEATURES += --features test_build + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test_unit test_integration test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +##------------------------------------------------------------------------------ +## Helpers for unit and integration test targets +##------------------------------------------------------------------------------ +define KERNEL_TEST_RUNNER +#!/usr/bin/env bash + + # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure + # this script executes from the root. + cd $(shell pwd) + + TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') + TEST_ELF_SYMS="$${TEST_ELF}_syms" + TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + + $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null + + # This overrides the two ENV variables. The other ENV variables that are required as input for + # the .mk file are set already because they are exported by this Makefile and this script is + # started by the same. + KERNEL_SYMBOLS_INPUT_ELF=$$TEST_ELF \ + KERNEL_SYMBOLS_OUTPUT_ELF=$$TEST_ELF_SYMS \ + $(MAKE) --no-print-directory -f kernel_symbols.mk > /dev/null 2>&1 + + $(OBJCOPY_CMD) $$TEST_ELF_SYMS $$TEST_BINARY + $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY +endef + +export KERNEL_TEST_RUNNER + +define test_prepare + @mkdir -p target + @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh + @chmod +x target/kernel_test_runner.sh +endef + +##------------------------------------------------------------------------------ +## Run unit test(s) +##------------------------------------------------------------------------------ +test_unit: + $(call color_header, "Compiling unit test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib + +##------------------------------------------------------------------------------ +## Run integration test(s) +##------------------------------------------------------------------------------ +test_integration: + $(call color_header, "Compiling integration test(s) - $(BSP)") + $(call test_prepare) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) + +test: test_boot test_unit test_integration + +endif diff --git a/20_timer_callbacks/README.md b/20_timer_callbacks/README.md new file mode 100644 index 000000000..062d5912e --- /dev/null +++ b/20_timer_callbacks/README.md @@ -0,0 +1,735 @@ +# Tutorial 20 - Timer Callbacks + +## tl;dr + +- The timer subsystem is extended so that it can be used to execute timeout callbacks in IRQ + context. + +## Note + +This chapter's code will be tightly coupled to follow-up tutorials which are yet to be developed. It +is therefore expected that this chapter's code is subject to change depending upon findings that are +yet to be made. + +Therefore, content for this README will be provided sometime later when all the pieces fit together. + +## Diff to previous +```diff + +diff -uNr 19_kernel_heap/kernel/Cargo.toml 20_timer_callbacks/kernel/Cargo.toml +--- 19_kernel_heap/kernel/Cargo.toml ++++ 20_timer_callbacks/kernel/Cargo.toml +@@ -1,6 +1,6 @@ + [package] + name = "mingo" +-version = "0.19.0" ++version = "0.20.0" + authors = ["Andre Richter "] + edition = "2021" + + +diff -uNr 19_kernel_heap/kernel/src/_arch/aarch64/time.rs 20_timer_callbacks/kernel/src/_arch/aarch64/time.rs +--- 19_kernel_heap/kernel/src/_arch/aarch64/time.rs ++++ 20_timer_callbacks/kernel/src/_arch/aarch64/time.rs +@@ -11,14 +11,17 @@ + //! + //! crate::time::arch_time + +-use crate::warn; ++use crate::{ ++ bsp::{self, exception}, ++ warn, ++}; + use aarch64_cpu::{asm::barrier, registers::*}; + use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, + }; +-use tock_registers::interfaces::Readable; ++use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + + //-------------------------------------------------------------------------------------------------- + // Private Definitions +@@ -160,3 +163,31 @@ + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} + } ++ ++/// The associated IRQ number. ++pub const fn timeout_irq() -> exception::asynchronous::IRQNumber { ++ bsp::exception::asynchronous::irq_map::ARM_NS_PHYSICAL_TIMER ++} ++ ++/// Program a timer IRQ to be fired after `delay` has passed. ++pub fn set_timeout_irq(due_time: Duration) { ++ let counter_value_target: GenericTimerCounterValue = match due_time.try_into() { ++ Err(msg) => { ++ warn!("set_timeout: {}. Skipping", msg); ++ return; ++ } ++ Ok(val) => val, ++ }; ++ ++ // Set the compare value register. ++ CNTP_CVAL_EL0.set(counter_value_target.0); ++ ++ // Kick off the timer. ++ CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::CLEAR); ++} ++ ++/// Conclude a pending timeout IRQ. ++pub fn conclude_timeout_irq() { ++ // Disable counting. De-asserts the IRQ. ++ CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); ++} + +diff -uNr 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/local_ic.rs 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/local_ic.rs +--- 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/local_ic.rs ++++ 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/local_ic.rs +@@ -0,0 +1,173 @@ ++// SPDX-License-Identifier: MIT OR Apache-2.0 ++// ++// Copyright (c) 2022-2023 Andre Richter ++ ++//! Local Interrupt Controller Driver. ++//! ++//! # Resources ++//! ++//! - ++ ++use super::{LocalIRQ, PendingIRQs}; ++use crate::{ ++ bsp::device_driver::common::MMIODerefWrapper, ++ exception, ++ memory::{Address, Virtual}, ++ synchronization, ++ synchronization::{IRQSafeNullLock, InitStateLock}, ++}; ++use alloc::vec::Vec; ++use tock_registers::{ ++ interfaces::{Readable, Writeable}, ++ register_structs, ++ registers::{ReadOnly, WriteOnly}, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ WORegisterBlock { ++ (0x00 => _reserved1), ++ (0x40 => CORE0_TIMER_INTERRUPT_CONTROL: WriteOnly), ++ (0x44 => @END), ++ } ++} ++ ++register_structs! { ++ #[allow(non_snake_case)] ++ RORegisterBlock { ++ (0x00 => _reserved1), ++ (0x60 => CORE0_INTERRUPT_SOURCE: ReadOnly), ++ (0x64 => @END), ++ } ++} ++ ++/// Abstraction for the WriteOnly parts of the associated MMIO registers. ++type WriteOnlyRegisters = MMIODerefWrapper; ++ ++/// Abstraction for the ReadOnly parts of the associated MMIO registers. ++type ReadOnlyRegisters = MMIODerefWrapper; ++ ++type HandlerTable = Vec>>; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Representation of the peripheral interrupt controller. ++pub struct LocalIC { ++ /// Access to write registers is guarded with a lock. ++ wo_registers: IRQSafeNullLock, ++ ++ /// Register read access is unguarded. ++ ro_registers: ReadOnlyRegisters, ++ ++ /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. ++ handler_table: InitStateLock, ++} ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl LocalIC { ++ // See datasheet. ++ const PERIPH_IRQ_MASK: u32 = (1 << 8); ++ ++ /// Create an instance. ++ /// ++ /// # Safety ++ /// ++ /// - The user must ensure to provide a correct MMIO start address. ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { ++ Self { ++ wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), ++ ro_registers: ReadOnlyRegisters::new(mmio_start_addr), ++ handler_table: InitStateLock::new(Vec::new()), ++ } ++ } ++ ++ /// Called by the kernel to bring up the device. ++ pub fn init(&self) { ++ self.handler_table ++ .write(|table| table.resize(LocalIRQ::MAX_INCLUSIVE + 1, None)); ++ } ++ ++ /// Query the list of pending IRQs. ++ fn pending_irqs(&self) -> PendingIRQs { ++ // Ignore the indicator bit for a peripheral IRQ. ++ PendingIRQs::new( ++ (self.ro_registers.CORE0_INTERRUPT_SOURCE.get() & !Self::PERIPH_IRQ_MASK).into(), ++ ) ++ } ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++use synchronization::interface::{Mutex, ReadWriteEx}; ++ ++impl exception::asynchronous::interface::IRQManager for LocalIC { ++ type IRQNumberType = LocalIRQ; ++ ++ fn register_handler( ++ &self, ++ irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ++ ) -> Result<(), &'static str> { ++ self.handler_table.write(|table| { ++ let irq_number = irq_handler_descriptor.number().get(); ++ ++ if table[irq_number].is_some() { ++ return Err("IRQ handler already registered"); ++ } ++ ++ table[irq_number] = Some(irq_handler_descriptor); ++ ++ Ok(()) ++ }) ++ } ++ ++ fn enable(&self, irq: &Self::IRQNumberType) { ++ self.wo_registers.lock(|regs| { ++ let enable_bit: u32 = 1 << (irq.get()); ++ ++ // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable ++ // bits are unaffected. So we don't need read and OR'ing here. ++ regs.CORE0_TIMER_INTERRUPT_CONTROL.set(enable_bit); ++ }); ++ } ++ ++ fn handle_pending_irqs<'irq_context>( ++ &'irq_context self, ++ _ic: &exception::asynchronous::IRQContext<'irq_context>, ++ ) { ++ self.handler_table.read(|table| { ++ for irq_number in self.pending_irqs() { ++ match table[irq_number] { ++ None => panic!("No handler registered for IRQ {}", irq_number), ++ Some(descriptor) => { ++ // Call the IRQ handler. Panics on failure. ++ descriptor.handler().handle().expect("Error handling IRQ"); ++ } ++ } ++ } ++ }) ++ } ++ ++ fn print_handler(&self) { ++ use crate::info; ++ ++ info!(" Local handler:"); ++ ++ self.handler_table.read(|table| { ++ for (i, opt) in table.iter().enumerate() { ++ if let Some(handler) = opt { ++ info!(" {: >3}. {}", i, handler.name()); ++ } ++ } ++ }); ++ } ++} + +diff -uNr 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +--- 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ++++ 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +@@ -4,6 +4,7 @@ + + //! Interrupt Controller Driver. + ++mod local_ic; + mod peripheral_ic; + + use crate::{ +@@ -40,6 +41,7 @@ + + /// Representation of the Interrupt Controller. + pub struct InterruptController { ++ local: local_ic::LocalIC, + periph: peripheral_ic::PeripheralIC, + } + +@@ -81,7 +83,7 @@ + } + + impl InterruptController { +- // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. ++ // Restrict to 3 for now. This makes the code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + +@@ -92,8 +94,12 @@ + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. +- pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { ++ pub const unsafe fn new( ++ local_mmio_start_addr: Address, ++ periph_mmio_start_addr: Address, ++ ) -> Self { + Self { ++ local: local_ic::LocalIC::new(local_mmio_start_addr), + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +@@ -111,6 +117,7 @@ + } + + unsafe fn init(&self) -> Result<(), &'static str> { ++ self.local.init(); + self.periph.init(); + + Ok(()) +@@ -125,7 +132,15 @@ + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { +- IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), ++ IRQNumber::Local(lirq) => { ++ let local_descriptor = IRQHandlerDescriptor::new( ++ lirq, ++ irq_handler_descriptor.name(), ++ irq_handler_descriptor.handler(), ++ ); ++ ++ self.local.register_handler(local_descriptor) ++ } + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, +@@ -140,7 +155,7 @@ + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { +- IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), ++ IRQNumber::Local(lirq) => self.local.enable(lirq), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } +@@ -149,11 +164,12 @@ + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { +- // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. ++ self.local.handle_pending_irqs(ic); + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { ++ self.local.print_handler(); + self.periph.print_handler(); + } + } + +diff -uNr 19_kernel_heap/kernel/src/bsp/raspberrypi/driver.rs 20_timer_callbacks/kernel/src/bsp/raspberrypi/driver.rs +--- 19_kernel_heap/kernel/src/bsp/raspberrypi/driver.rs ++++ 20_timer_callbacks/kernel/src/bsp/raspberrypi/driver.rs +@@ -73,6 +73,12 @@ + /// This must be called only after successful init of the memory subsystem. + #[cfg(feature = "bsp_rpi3")] + unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { ++ let local_mmio_descriptor = MMIODescriptor::new(mmio::LOCAL_IC_START, mmio::LOCAL_IC_SIZE); ++ let local_virt_addr = memory::mmu::kernel_map_mmio( ++ device_driver::InterruptController::COMPATIBLE, ++ &local_mmio_descriptor, ++ )?; ++ + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( +@@ -80,7 +86,10 @@ + &periph_mmio_descriptor, + )?; + +- INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); ++ INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new( ++ local_virt_addr, ++ periph_virt_addr, ++ )); + + Ok(()) + } + +diff -uNr 19_kernel_heap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs 20_timer_callbacks/kernel/src/bsp/raspberrypi/exception/asynchronous.rs +--- 19_kernel_heap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ++++ 20_timer_callbacks/kernel/src/bsp/raspberrypi/exception/asynchronous.rs +@@ -13,16 +13,24 @@ + /// Export for reuse in generic asynchronous.rs. + pub use bsp::device_driver::IRQNumber; + ++/// The IRQ map. + #[cfg(feature = "bsp_rpi3")] +-pub(in crate::bsp) mod irq_map { +- use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; ++pub mod irq_map { ++ use super::bsp::device_driver::{IRQNumber, LocalIRQ, PeripheralIRQ}; + +- pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); ++ /// The non-secure physical timer IRQ number. ++ pub const ARM_NS_PHYSICAL_TIMER: IRQNumber = IRQNumber::Local(LocalIRQ::new(1)); ++ ++ pub(in crate::bsp) const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); + } + ++/// The IRQ map. + #[cfg(feature = "bsp_rpi4")] +-pub(in crate::bsp) mod irq_map { ++pub mod irq_map { + use super::bsp::device_driver::IRQNumber; + +- pub const PL011_UART: IRQNumber = IRQNumber::new(153); ++ /// The non-secure physical timer IRQ number. ++ pub const ARM_NS_PHYSICAL_TIMER: IRQNumber = IRQNumber::new(30); ++ ++ pub(in crate::bsp) const PL011_UART: IRQNumber = IRQNumber::new(153); + } + +diff -uNr 19_kernel_heap/kernel/src/bsp/raspberrypi/memory.rs 20_timer_callbacks/kernel/src/bsp/raspberrypi/memory.rs +--- 19_kernel_heap/kernel/src/bsp/raspberrypi/memory.rs ++++ 20_timer_callbacks/kernel/src/bsp/raspberrypi/memory.rs +@@ -124,6 +124,9 @@ + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + ++ pub const LOCAL_IC_START: Address = Address::new(0x4000_0000); ++ pub const LOCAL_IC_SIZE: usize = 0x100; ++ + pub const END: Address = Address::new(0x4001_0000); + } + + +diff -uNr 19_kernel_heap/kernel/src/main.rs 20_timer_callbacks/kernel/src/main.rs +--- 19_kernel_heap/kernel/src/main.rs ++++ 20_timer_callbacks/kernel/src/main.rs +@@ -30,6 +30,11 @@ + exception::handling_init(); + memory::init(); + ++ // Initialize the timer subsystem. ++ if let Err(x) = time::init() { ++ panic!("Error initializing timer subsystem: {}", x); ++ } ++ + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); +@@ -52,6 +57,9 @@ + + /// The main function running after the early init. + fn kernel_main() -> ! { ++ use alloc::boxed::Box; ++ use core::time::Duration; ++ + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + +@@ -78,6 +86,11 @@ + info!("Kernel heap:"); + memory::heap_alloc::kernel_heap_allocator().print_usage(); + ++ time::time_manager().set_timeout_once(Duration::from_secs(5), Box::new(|| info!("Once 5"))); ++ time::time_manager().set_timeout_once(Duration::from_secs(3), Box::new(|| info!("Once 2"))); ++ time::time_manager() ++ .set_timeout_periodic(Duration::from_secs(1), Box::new(|| info!("Periodic 1 sec"))); ++ + info!("Echoing input now"); + cpu::wait_forever(); + } + +diff -uNr 19_kernel_heap/kernel/src/time.rs 20_timer_callbacks/kernel/src/time.rs +--- 19_kernel_heap/kernel/src/time.rs ++++ 20_timer_callbacks/kernel/src/time.rs +@@ -3,19 +3,54 @@ + // Copyright (c) 2020-2023 Andre Richter + + //! Timer primitives. ++//! ++//! # Resources ++//! ++//! - ++//! - + + #[cfg(target_arch = "aarch64")] + #[path = "_arch/aarch64/time.rs"] + mod arch_time; + +-use core::time::Duration; ++use crate::{ ++ driver, exception, ++ exception::asynchronous::IRQNumber, ++ synchronization::{interface::Mutex, IRQSafeNullLock}, ++ warn, ++}; ++use alloc::{boxed::Box, vec::Vec}; ++use core::{ ++ sync::atomic::{AtomicBool, Ordering}, ++ time::Duration, ++}; ++ ++//-------------------------------------------------------------------------------------------------- ++// Private Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++struct Timeout { ++ due_time: Duration, ++ period: Option, ++ callback: TimeoutCallback, ++} ++ ++struct OrderedTimeoutQueue { ++ // Can be replaced with a BinaryHeap once it's new() becomes const. ++ inner: Vec, ++} + + //-------------------------------------------------------------------------------------------------- + // Public Definitions + //-------------------------------------------------------------------------------------------------- + ++/// The callback type used by timer IRQs. ++pub type TimeoutCallback = Box; ++ + /// Provides time management functions. +-pub struct TimeManager; ++pub struct TimeManager { ++ queue: IRQSafeNullLock, ++} + + //-------------------------------------------------------------------------------------------------- + // Global instances +@@ -24,6 +59,46 @@ + static TIME_MANAGER: TimeManager = TimeManager::new(); + + //-------------------------------------------------------------------------------------------------- ++// Private Code ++//-------------------------------------------------------------------------------------------------- ++ ++impl Timeout { ++ pub fn is_periodic(&self) -> bool { ++ self.period.is_some() ++ } ++ ++ pub fn refresh(&mut self) { ++ if let Some(delay) = self.period { ++ self.due_time += delay; ++ } ++ } ++} ++ ++impl OrderedTimeoutQueue { ++ pub const fn new() -> Self { ++ Self { inner: Vec::new() } ++ } ++ ++ pub fn push(&mut self, timeout: Timeout) { ++ self.inner.push(timeout); ++ ++ // Note reverse compare order so that earliest expiring item is at end of vec. We do this so ++ // that we can use Vec::pop below to retrieve the item that is next due. ++ self.inner.sort_by(|a, b| b.due_time.cmp(&a.due_time)); ++ } ++ ++ pub fn peek_next_due_time(&self) -> Option { ++ let timeout = self.inner.last()?; ++ ++ Some(timeout.due_time) ++ } ++ ++ pub fn pop(&mut self) -> Option { ++ self.inner.pop() ++ } ++} ++ ++//-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- + +@@ -33,9 +108,14 @@ + } + + impl TimeManager { ++ /// Compatibility string. ++ pub const COMPATIBLE: &'static str = "ARM Architectural Timer"; ++ + /// Create an instance. + pub const fn new() -> Self { +- Self ++ Self { ++ queue: IRQSafeNullLock::new(OrderedTimeoutQueue::new()), ++ } + } + + /// The timer's resolution. +@@ -54,4 +134,130 @@ + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } ++ ++ /// Set a timeout. ++ fn set_timeout(&self, timeout: Timeout) { ++ self.queue.lock(|queue| { ++ queue.push(timeout); ++ ++ arch_time::set_timeout_irq(queue.peek_next_due_time().unwrap()); ++ }); ++ } ++ ++ /// Set a one-shot timeout. ++ pub fn set_timeout_once(&self, delay: Duration, callback: TimeoutCallback) { ++ let timeout = Timeout { ++ due_time: self.uptime() + delay, ++ period: None, ++ callback, ++ }; ++ ++ self.set_timeout(timeout); ++ } ++ ++ /// Set a periodic timeout. ++ pub fn set_timeout_periodic(&self, delay: Duration, callback: TimeoutCallback) { ++ let timeout = Timeout { ++ due_time: self.uptime() + delay, ++ period: Some(delay), ++ callback, ++ }; ++ ++ self.set_timeout(timeout); ++ } ++} ++ ++/// Initialize the timer subsystem. ++pub fn init() -> Result<(), &'static str> { ++ static INIT_DONE: AtomicBool = AtomicBool::new(false); ++ if INIT_DONE.load(Ordering::Relaxed) { ++ return Err("Init already done"); ++ } ++ ++ let timer_descriptor = ++ driver::DeviceDriverDescriptor::new(time_manager(), None, Some(arch_time::timeout_irq())); ++ driver::driver_manager().register_driver(timer_descriptor); ++ ++ INIT_DONE.store(true, Ordering::Relaxed); ++ Ok(()) ++} ++ ++//------------------------------------------------------------------------------ ++// OS Interface Code ++//------------------------------------------------------------------------------ ++ ++impl driver::interface::DeviceDriver for TimeManager { ++ type IRQNumberType = IRQNumber; ++ ++ fn compatible(&self) -> &'static str { ++ Self::COMPATIBLE ++ } ++ ++ fn register_and_enable_irq_handler( ++ &'static self, ++ irq_number: &Self::IRQNumberType, ++ ) -> Result<(), &'static str> { ++ use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; ++ ++ let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); ++ ++ irq_manager().register_handler(descriptor)?; ++ irq_manager().enable(irq_number); ++ ++ Ok(()) ++ } ++} ++ ++impl exception::asynchronous::interface::IRQHandler for TimeManager { ++ fn handle(&self) -> Result<(), &'static str> { ++ arch_time::conclude_timeout_irq(); ++ ++ let maybe_timeout: Option = self.queue.lock(|queue| { ++ let next_due_time = queue.peek_next_due_time()?; ++ if next_due_time > self.uptime() { ++ return None; ++ } ++ ++ let mut timeout = queue.pop().unwrap(); ++ ++ // Refresh as early as possible to prevent drift. ++ if timeout.is_periodic() { ++ timeout.refresh(); ++ } ++ ++ Some(timeout) ++ }); ++ ++ let timeout = match maybe_timeout { ++ None => { ++ warn!("Spurious timeout IRQ"); ++ return Ok(()); ++ } ++ Some(t) => t, ++ }; ++ ++ // Important: Call the callback while not holding any lock, because the callback might ++ // attempt to modify data that is protected by a lock (in particular, the timeout queue ++ // itself). ++ (timeout.callback)(); ++ ++ self.queue.lock(|queue| { ++ if timeout.is_periodic() { ++ // There might be some overhead involved in the periodic path, because the timeout ++ // item is first popped from the underlying Vec and then pushed back again. It could ++ // be faster to keep the item in the queue and find a way to work with a reference ++ // to it. ++ // ++ // We are not going this route on purpose, though. It allows to keep the code simple ++ // and the focus on the high-level concepts. ++ queue.push(timeout); ++ }; ++ ++ if let Some(due_time) = queue.peek_next_due_time() { ++ arch_time::set_timeout_irq(due_time); ++ } ++ }); ++ ++ Ok(()) ++ } + } + +diff -uNr 19_kernel_heap/kernel/tests/boot_test_string.rb 20_timer_callbacks/kernel/tests/boot_test_string.rb +--- 19_kernel_heap/kernel/tests/boot_test_string.rb ++++ 20_timer_callbacks/kernel/tests/boot_test_string.rb +@@ -1,3 +1,3 @@ + # frozen_string_literal: true + +-EXPECTED_PRINT = 'Echoing input now' ++EXPECTED_PRINT = 'Once 5' + +``` diff --git a/20_timer_callbacks/kernel/Cargo.toml b/20_timer_callbacks/kernel/Cargo.toml new file mode 100644 index 000000000..4a3b76d3e --- /dev/null +++ b/20_timer_callbacks/kernel/Cargo.toml @@ -0,0 +1,72 @@ +[package] +name = "mingo" +version = "0.20.0" +authors = ["Andre Richter "] +edition = "2021" + +[features] +default = [] +debug_prints = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] +test_build = ["qemu-exit"] + +##------------------------------------------------------------------------------------------------- +## Dependencies +##------------------------------------------------------------------------------------------------- + +[dependencies] +test-types = { path = "../libraries/test-types" } +debug-symbol-types = { path = "../libraries/debug-symbol-types" } +linked_list_allocator = { version = "0.10.x", default-features = false, features = ["const_mut_refs"] } + +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } +qemu-exit = { version = "3.x.x", optional = true } + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } + +##------------------------------------------------------------------------------------------------- +## Testing +##------------------------------------------------------------------------------------------------- + +[dev-dependencies] +test-macros = { path = "../libraries/test-macros" } + +# Unit tests are done in the library part of the kernel. +[lib] +name = "libkernel" +test = true + +# Disable unit tests for the kernel binary. +[[bin]] +name = "kernel" +path = "src/main.rs" +test = false + +# List of tests without harness. +[[test]] +name = "00_console_sanity" +harness = false + +[[test]] +name = "02_exception_sync_page_fault" +harness = false + +[[test]] +name = "03_exception_restore_sanity" +harness = false + +[[test]] +name = "05_backtrace_sanity" +harness = false + +[[test]] +name = "06_backtrace_invalid_frame" +harness = false + +[[test]] +name = "07_backtrace_invalid_link" +harness = false diff --git a/20_timer_callbacks/kernel/build.rs b/20_timer_callbacks/kernel/build.rs new file mode 100644 index 000000000..cab00bb37 --- /dev/null +++ b/20_timer_callbacks/kernel/build.rs @@ -0,0 +1,20 @@ +use std::{env, fs, process}; + +fn main() { + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; + + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/backtrace.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/backtrace.rs new file mode 100644 index 000000000..c2fb8dcb4 --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/backtrace.rs @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Architectural backtracing support. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::backtrace::arch_backtrace + +use crate::{ + backtrace::BacktraceItem, + memory::{Address, Virtual}, +}; +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// A Stack frame record. +/// +/// # Note +/// +/// The convention is that `previous_record` is valid as long as it contains a non-null value. +/// Therefore, it is possible to type the member as `Option<&StackFrameRecord>` because of Rust's +/// `null-pointer optimization`. +#[repr(C)] +struct StackFrameRecord<'a> { + previous_record: Option<&'a StackFrameRecord<'a>>, + link: Address, +} + +struct StackFrameRecordIterator<'a> { + cur: &'a StackFrameRecord<'a>, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl<'a> Iterator for StackFrameRecordIterator<'a> { + type Item = BacktraceItem; + + fn next(&mut self) -> Option { + static ABORT_FRAME: StackFrameRecord = StackFrameRecord { + previous_record: None, + link: Address::new(0), + }; + + // If previous is None, this is the root frame, so iteration will stop here. + let previous = self.cur.previous_record?; + + // Need to abort if the pointer to the previous frame record is invalid. + let prev_addr = Address::::new(previous as *const _ as usize); + if !prev_addr.is_valid_stack_addr() { + // This allows to return the error and then stop on the next iteration. + self.cur = &ABORT_FRAME; + return Some(BacktraceItem::InvalidFramePointer(prev_addr)); + } + + let ret = if !self.cur.link.is_valid_code_addr() { + Some(BacktraceItem::InvalidLink(self.cur.link)) + } else { + // The link points to the instruction to be executed _after_ returning from a branch. + // However, we want to show the instruction that caused the branch, so subtract by one + // instruction. + // + // This might be called from panic!, so it must not panic itself on the subtraction. + let link = if self.cur.link >= Address::new(4) { + self.cur.link - 4 + } else { + self.cur.link + }; + + Some(BacktraceItem::Link(link)) + }; + + // Advance the iterator. + self.cur = previous; + + ret + } +} + +fn stack_frame_record_iterator<'a>() -> Option> { + let fp = Address::::new(FP.get() as usize); + if !fp.is_valid_stack_addr() { + return None; + } + + Some(StackFrameRecordIterator { + cur: unsafe { &*(fp.as_usize() as *const _) }, + }) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Architectural implementation of the backtrace. +pub fn backtrace(f: impl FnOnce(Option<&mut dyn Iterator>)) { + f(stack_frame_record_iterator().as_mut().map(|s| s as _)) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(feature = "test_build")] +#[inline(always)] +/// Hack for corrupting the previous frame address in the current stack frame. +/// +/// # Safety +/// +/// - To be used only by testing code. +pub unsafe fn corrupt_previous_frame_addr() { + let sf = FP.get() as *mut usize; + *sf = 0x123; +} + +#[cfg(feature = "test_build")] +#[inline(always)] +/// Hack for corrupting the link in the current stack frame. +/// +/// # Safety +/// +/// - To be used only by testing code. +pub unsafe fn corrupt_link() { + let sf = FP.get() as *mut StackFrameRecord; + (*sf).link = Address::new(0x456); +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/cpu.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/cpu.rs new file mode 100644 index 000000000..2d0104736 --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/cpu.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +pub use asm::nop; + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +use qemu_exit::QEMUExit; + +#[cfg(feature = "test_build")] +const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); + +/// Make the host QEMU binary execute `exit(1)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_failure() -> ! { + QEMU_EXIT_HANDLE.exit_failure() +} + +/// Make the host QEMU binary execute `exit(0)`. +#[cfg(feature = "test_build")] +pub fn qemu_exit_success() -> ! { + QEMU_EXIT_HANDLE.exit_success() +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/boot.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..b8033fbe8 --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use crate::{memory, memory::Address}; +use aarch64_cpu::{asm, registers::*}; +use core::{ + arch::global_asm, + sync::atomic::{compiler_fence, Ordering}, +}; +use tock_registers::interfaces::Writeable; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(virt_kernel_init_addr); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(virt_boot_core_stack_end_exclusive_addr); +} + +/// Reset the backtrace by setting link register and frame pointer to zero. +/// +/// # Safety +/// +/// - This function must only be used immediately before entering EL1. +#[inline(always)] +unsafe fn prepare_backtrace_reset() { + compiler_fence(Ordering::SeqCst); + FP.set(0); + LR.set(0); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. +#[no_mangle] +pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) -> ! { + prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr, + virt_kernel_init_addr, + ); + + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + + // Make the function we return to the root of a backtrace. + prepare_backtrace_reset(); + + // Use `eret` to "return" to EL1. Since virtual memory will already be enabled, this results in + // execution of kernel_init() in EL1 from its _virtual address_. + asm::eret() +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/boot.s b/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..65d71b1a7 --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +// Load the address of a symbol into a register, absolute. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_ABS register, symbol + movz \register, #:abs_g3:\symbol + movk \register, #:abs_g2_nc:\symbol + movk \register, #:abs_g1_nc:\symbol + movk \register, #:abs_g0_nc:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Load the base address of the kernel's translation tables. + ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + + // Load the _absolute_ addresses of the following symbols. Since the kernel is linked at + // the top of the 64 bit address space, these are effectively virtual addresses. + ADR_ABS x1, __boot_core_stack_end_exclusive + ADR_ABS x2, kernel_init + + // Load the PC-relative address of the stack and set the stack pointer. + // + // Since _start() is the first function that runs after the firmware has loaded the kernel + // into memory, retrieving this symbol PC-relative returns the "physical" address. + // + // Setting the stack pointer to this value ensures that anything that still runs in EL2, + // until the kernel returns to EL1 with the MMU enabled, works as well. After the return to + // EL1, the virtual address of the stack retrieved above will be used. + ADR_REL x3, __boot_core_stack_end_exclusive + mov sp, x3 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x4, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x5, CNTFRQ_EL0 + cmp x5, xzr + b.eq .L_parking_loop + str w5, [x4] + + // Jump to Rust code. x0, x1 and x2 hold the function arguments provided to _start_rust(). + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/smp.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/smp.rs new file mode 100644 index 000000000..491920389 --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/exception.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/exception.rs new file mode 100644 index 000000000..ab4640815 --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/exception.rs @@ -0,0 +1,325 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use crate::{exception, memory, symbols}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!( + include_str!("exception.s"), + CONST_ESR_EL1_EC_SHIFT = const 26, + CONST_ESR_EL1_EC_VALUE_SVC64 = const 0x15 +); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + #[cfg(feature = "test_build")] + { + const TEST_SVC_ID: u64 = 0x1337; + + if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { + if e.esr_el1.iss() == TEST_SVC_ID { + return; + } + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } + + #[cfg(feature = "test_build")] + #[inline(always)] + fn iss(&self) -> u64 { + self.0.read(ESR_EL1::ISS) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!( + f, + " Symbol: {}", + match symbols::lookup_symbol(memory::Address::new(self.elr_el1 as usize)) { + Some(sym) => sym.name(), + _ => "Symbol not found", + } + )?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x % 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/exception.s b/20_timer_callbacks/kernel/src/_arch/aarch64/exception.s new file mode 100644 index 000000000..a806a276b --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/exception.s @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler is_lower_el is_sync +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 18 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // Build a stack frame for backtracing. +.if \is_lower_el == 1 + // If we came from a lower EL, make it a root frame (by storing zero) so that the kernel + // does not attempt to trace into userspace. + stp xzr, xzr, [sp, #16 * 17] +.else + // For normal branches, the link address points to the instruction to be executed _after_ + // returning from a branch. In a backtrace, we want to show the instruction that caused the + // branch, though. That is why code in backtrace.rs subtracts 4 (length of one instruction) + // from the link address. + // + // Here we have a special case, though, because ELR_EL1 is used instead of LR to build the + // stack frame, so that it becomes possible to trace beyond an exception. Hence, it must be + // considered that semantics for ELR_EL1 differ from case to case. + // + // Unless an "exception generating instruction" was executed, ELR_EL1 already points to the + // the correct instruction, and hence the subtraction by 4 in backtrace.rs would yield wrong + // results. To cover for this, 4 is added to ELR_EL1 below unless the cause of exception was + // an SVC instruction. BRK and HLT are "exception generating instructions" as well, but they + // are not expected and therefore left out for now. + // + // For reference: Search for "preferred exception return address" in the Architecture + // Reference Manual for ARMv8-A. +.if \is_sync == 1 + lsr w3, w3, {CONST_ESR_EL1_EC_SHIFT} // w3 = ESR_EL1.EC + cmp w3, {CONST_ESR_EL1_EC_VALUE_SVC64} // w3 == SVC64 ? + b.eq 1f +.endif + add x1, x1, #4 +1: + stp x29, x1, [sp, #16 * 17] +.endif + + // Set the frame pointer to the stack frame record. + add x29, sp, #16 * 17 + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous, 0, 1 +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq, 0, 0 +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror, 0, 0 + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous, 0, 1 +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq, 0, 0 +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror, 0, 0 + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous, 1, 1 +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq, 1, 0 +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror, 1, 0 + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous, 1, 0 +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq, 1, 0 +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror, 1, 0 +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 18 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/exception/asynchronous.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/exception/asynchronous.rs new file mode 100644 index 000000000..811ef138e --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/memory/mmu.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/memory/mmu.rs new file mode 100644 index 000000000..984b2e04f --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::{mmu::TranslationGranule, Address, Physical}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE % Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + #[inline(always)] + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + #[inline(always)] + fn configure_translation_control(&self) { + let t1sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI1::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG1::KiB_64 + + TCR_EL1::SH1::Inner + + TCR_EL1::ORGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD1::EnableTTBR1Walks + + TCR_EL1::A1::TTBR1 + + TCR_EL1::T1SZ.val(t1sz) + + TCR_EL1::EPD0::DisableTTBR0Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Set the "Translation Table Base Register". + TTBR1_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs new file mode 100644 index 000000000..21fae3b82 --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,521 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, + memory::{ + self, + mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, + }, + Address, Physical, Virtual, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn virt_start_addr(&self) -> Address; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], + + /// Have the tables been initialized? + initialized: bool, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl StartAddr for [T; N] { + fn virt_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +/// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. +impl convert::TryFrom> for AttributeFields { + type Error = &'static str; + + fn try_from( + desc: InMemoryRegister, + ) -> Result { + let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { + memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, + memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, + _ => return Err("Unexpected memory attribute"), + }; + + let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, + _ => return Err("Unexpected access permission"), + }; + + let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; + + Ok(AttributeFields { + mem_attributes, + acc_perms, + execute_never, + }) + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_page_addr( + phys_output_page_addr: PageAddress, + attribute_fields: &AttributeFields, + ) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } + + /// Returns the valid bit. + fn is_valid(&self) -> bool { + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } + + /// Returns the output page. + fn output_page_addr(&self) -> PageAddress { + let shifted = InMemoryRegister::::new(self.value) + .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; + + PageAddress::from(shifted << Granule64KiB::SHIFT) + } + + /// Returns the attributes. + fn try_attributes(&self) -> Result { + InMemoryRegister::::new(self.value).try_into() + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromTop = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; + + type TableStartFromBottom = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; +} + +impl + FixedSizeTranslationTable +{ + const START_FROM_TOP_OFFSET: Address = + Address::new((usize::MAX - (Granule512MiB::SIZE * NUM_TABLES)) + 1); + + /// Create an instance. + #[allow(clippy::assertions_on_constants)] + const fn _new(for_precompute: bool) -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + initialized: for_precompute, + } + } + + pub const fn new_for_precompute() -> Self { + Self::_new(true) + } + + #[cfg(test)] + pub fn new_for_runtime() -> Self { + Self::_new(false) + } + + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { + let mut addr = virt_page_addr.into_inner(); + + if START_FROM_TOP { + addr = addr - Self::START_FROM_TOP_OFFSET; + } + + let lvl2_index = addr.as_usize() >> Granule512MiB::SHIFT; + let lvl3_index = (addr.as_usize() & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); + } + + Ok((lvl2_index, lvl3_index)) + } + + /// Returns the PageDescriptor corresponding to the supplied page address. + #[inline(always)] + fn page_descriptor_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<&PageDescriptor, &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &self.lvl3[lvl2_index][lvl3_index]; + + Ok(desc) + } + + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. + #[inline(always)] + fn set_page_descriptor_from_page_addr( + &mut self, + virt_page_addr: PageAddress, + new_desc: &PageDescriptor, + ) -> Result<(), &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &mut self.lvl3[lvl2_index][lvl3_index]; + + if desc.is_valid() { + return Err("Virtual page is already mapped"); + } + + *desc = *new_desc; + Ok(()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl + memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable +{ + fn init(&mut self) -> Result<(), &'static str> { + if self.initialized { + return Ok(()); + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { + let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); + let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; + + Ok(()) + } + + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + assert!(self.initialized, "Translation tables not initialized"); + + if virt_region.size() != phys_region.size() { + return Err("Tried to map memory regions with unequal sizes"); + } + + if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() + { + return Err("Tried to map outside of physical address space"); + } + + let iter = phys_region.into_iter().zip(virt_region.into_iter()); + for (phys_page_addr, virt_page_addr) in iter { + let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); + let virt_page = virt_page_addr; + + self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; + } + + Ok(()) + } + + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str> { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + Ok(page_desc.output_page_addr()) + } + + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + page_desc.try_attributes() + } + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str> { + let virt_page = PageAddress::from(virt_addr.align_down_page()); + let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; + + Ok(phys_page.into_inner() + virt_addr.offset_into_page()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1, true>; + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Check if the size of `struct TableDescriptor` is as expected. + #[kernel_test] + fn size_of_tabledescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } + + /// Check if the size of `struct PageDescriptor` is as expected. + #[kernel_test] + fn size_of_pagedescriptor_equals_64_bit() { + assert_eq!( + core::mem::size_of::(), + core::mem::size_of::() + ); + } +} diff --git a/20_timer_callbacks/kernel/src/_arch/aarch64/time.rs b/20_timer_callbacks/kernel/src/_arch/aarch64/time.rs new file mode 100644 index 000000000..37ebf44be --- /dev/null +++ b/20_timer_callbacks/kernel/src/_arch/aarch64/time.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::{ + bsp::{self, exception}, + warn, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} + +/// The associated IRQ number. +pub const fn timeout_irq() -> exception::asynchronous::IRQNumber { + bsp::exception::asynchronous::irq_map::ARM_NS_PHYSICAL_TIMER +} + +/// Program a timer IRQ to be fired after `delay` has passed. +pub fn set_timeout_irq(due_time: Duration) { + let counter_value_target: GenericTimerCounterValue = match due_time.try_into() { + Err(msg) => { + warn!("set_timeout: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + + // Set the compare value register. + CNTP_CVAL_EL0.set(counter_value_target.0); + + // Kick off the timer. + CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::CLEAR); +} + +/// Conclude a pending timeout IRQ. +pub fn conclude_timeout_irq() { + // Disable counting. De-asserts the IRQ. + CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); +} diff --git a/20_timer_callbacks/kernel/src/backtrace.rs b/20_timer_callbacks/kernel/src/backtrace.rs new file mode 100644 index 000000000..a6af2fccc --- /dev/null +++ b/20_timer_callbacks/kernel/src/backtrace.rs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Backtracing support. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/backtrace.rs"] +mod arch_backtrace; + +use crate::{ + memory::{Address, Virtual}, + symbols, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(feature = "test_build")] +pub use arch_backtrace::{corrupt_link, corrupt_previous_frame_addr}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A backtrace item. +#[allow(missing_docs)] +pub enum BacktraceItem { + InvalidFramePointer(Address), + InvalidLink(Address), + Link(Address), +} + +/// Pseudo-struct for printing a backtrace using its fmt::Display implementation. +pub struct Backtrace; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for Backtrace { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "Backtrace:")?; + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + )?; + writeln!( + f, + " Address Function containing address" + )?; + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + )?; + + let mut fmt_res: fmt::Result = Ok(()); + let trace_formatter = + |maybe_iter: Option<&mut dyn Iterator>| match maybe_iter { + None => fmt_res = writeln!(f, "ERROR! No valid stack frame found"), + Some(iter) => { + // Since the backtrace is printed, the first function is always + // core::fmt::write. Skip 1 so it is excluded and doesn't bloat the output. + for (i, backtrace_res) in iter.skip(1).enumerate() { + match backtrace_res { + BacktraceItem::InvalidFramePointer(addr) => { + fmt_res = writeln!( + f, + " {:>2}. ERROR! \ + Encountered invalid frame pointer ({}) during backtrace", + i + 1, + addr + ); + } + BacktraceItem::InvalidLink(addr) => { + fmt_res = writeln!( + f, + " {:>2}. ERROR! \ + Link address ({}) is not contained in kernel .text section", + i + 1, + addr + ); + } + BacktraceItem::Link(addr) => { + fmt_res = writeln!( + f, + " {:>2}. {:016x} | {:<50}", + i + 1, + addr.as_usize(), + match symbols::lookup_symbol(addr) { + Some(sym) => sym.name(), + _ => "Symbol not found", + } + ) + } + }; + + if fmt_res.is_err() { + break; + } + } + } + }; + + arch_backtrace::backtrace(trace_formatter); + fmt_res?; + + writeln!( + f, + " ----------------------------------------------------------------------------------------------" + ) + } +} diff --git a/20_timer_callbacks/kernel/src/bsp.rs b/20_timer_callbacks/kernel/src/bsp.rs new file mode 100644 index 000000000..246973bc0 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp.rs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Conditional reexporting of Board Support Packages. + +mod device_driver; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod raspberrypi; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use raspberrypi::*; diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver.rs b/20_timer_callbacks/kernel/src/bsp/device_driver.rs new file mode 100644 index 000000000..2dfaec8d6 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(feature = "bsp_rpi4")] +mod arm; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/arm.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/arm.rs new file mode 100644 index 000000000..8d1cbfbd8 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2.rs new file mode 100644 index 000000000..7dabf7934 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; +use alloc::vec::Vec; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = Vec>>; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 1019; + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new( + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, + ) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new(Vec::new()), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.handler_table + .write(|table| table.resize(IRQNumber::MAX_INCLUSIVE + 1, None)); + + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs new file mode 100644 index 000000000..0fd16bb38 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs new file mode 100644 index 000000000..1fc9d70e9 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, + state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num % 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/bcm.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm.rs new file mode 100644 index 000000000..7b7c288b7 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; +pub use bcm2xxx_pl011_uart::*; diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs new file mode 100644 index 000000000..812156f44 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::time; + use core::time::Duration; + + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + time::time_manager().spin_for(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + time::time_manager().spin_for(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs new file mode 100644 index 000000000..d32bd8db4 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod local_ic; +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + local: local_ic::LocalIC, + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes the code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new( + local_mmio_start_addr: Address, + periph_mmio_start_addr: Address, + ) -> Self { + Self { + local: local_ic::LocalIC::new(local_mmio_start_addr), + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.local.init(); + self.periph.init(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(lirq) => { + let local_descriptor = IRQHandlerDescriptor::new( + lirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.local.register_handler(local_descriptor) + } + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(lirq) => self.local.enable(lirq), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.local.handle_pending_irqs(ic); + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.local.print_handler(); + self.periph.print_handler(); + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/local_ic.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/local_ic.rs new file mode 100644 index 000000000..b5e4974be --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/local_ic.rs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Local Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{LocalIRQ, PendingIRQs}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use alloc::vec::Vec; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x40 => CORE0_TIMER_INTERRUPT_CONTROL: WriteOnly), + (0x44 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x60 => CORE0_INTERRUPT_SOURCE: ReadOnly), + (0x64 => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = Vec>>; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct LocalIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl LocalIC { + // See datasheet. + const PERIPH_IRQ_MASK: u32 = (1 << 8); + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new(Vec::new()), + } + } + + /// Called by the kernel to bring up the device. + pub fn init(&self) { + self.handler_table + .write(|table| table.resize(LocalIRQ::MAX_INCLUSIVE + 1, None)); + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + // Ignore the indicator bit for a peripheral IRQ. + PendingIRQs::new( + (self.ro_registers.CORE0_INTERRUPT_SOURCE.get() & !Self::PERIPH_IRQ_MASK).into(), + ) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for LocalIC { + type IRQNumberType = LocalIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_bit: u32 = 1 << (irq.get()); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + regs.CORE0_TIMER_INTERRUPT_CONTROL.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Local handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs new file mode 100644 index 000000000..029c1e742 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, + synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use alloc::vec::Vec; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = Vec>>; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new(Vec::new()), + } + } + + /// Called by the kernel to bring up the device. + pub fn init(&self) { + self.handler_table + .write(|table| table.resize(PeripheralIRQ::MAX_INCLUSIVE + 1, None)); + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() % 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs new file mode 100644 index 000000000..3d5809755 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,516 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Send a slice of characters. + fn write_array(&mut self, a: &[char]) { + for c in a { + self.write_char(*c); + } + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { + Self { + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_array(&self, a: &[char]) { + self.inner.lock(|inner| inner.write_array(a)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/device_driver/common.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/common.rs new file mode 100644 index 000000000..3ce1d8d81 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/common.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use crate::memory::{Address, Virtual}; +use core::{fmt, marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: Address, + phantom: PhantomData T>, +} + +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: Address) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr.as_usize() as *const _) } + } +} + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi.rs b/20_timer_callbacks/kernel/src/bsp/raspberrypi.rs new file mode 100644 index 000000000..30421dfa6 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi.rs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Top-level BSP file for the Raspberry Pi 3 and 4. + +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi/cpu.rs b/20_timer_callbacks/kernel/src/bsp/raspberrypi/cpu.rs new file mode 100644 index 000000000..65cf5abbe --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used by `arch` code to find the early boot core. +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi/driver.rs b/20_timer_callbacks/kernel/src/bsp/raspberrypi/driver.rs new file mode 100644 index 000000000..d02909e3a --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, + memory, + memory::mmu::MMIODescriptor, +}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering}, +}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi3")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); + +#[cfg(feature = "bsp_rpi4")] +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the UART driver. +unsafe fn post_init_uart() -> Result<(), &'static str> { + console::register_console(PL011_UART.assume_init_ref()); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_gpio() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; + + GPIO.write(device_driver::GPIO::new(virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +unsafe fn post_init_gpio() -> Result<(), &'static str> { + GPIO.assume_init_ref().map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi3")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let local_mmio_descriptor = MMIODescriptor::new(mmio::LOCAL_IC_START, mmio::LOCAL_IC_SIZE); + let local_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &local_mmio_descriptor, + )?; + + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &periph_mmio_descriptor, + )?; + + INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new( + local_virt_addr, + periph_virt_addr, + )); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi4")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); + let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; + + let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); + let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; + + INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the interrupt controller driver. +unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + PL011_UART.assume_init_ref(), + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_gpio() -> Result<(), &'static str> { + instantiate_gpio()?; + + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( + GPIO.assume_init_ref(), + Some(post_init_gpio), + None, + ); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { + instantiate_interrupt_controller()?; + + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + INTERRUPT_CONTROLLER.assume_init_ref(), + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + driver_interrupt_controller()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +/// Minimal code needed to bring up the console in QEMU (for testing only). This is often less steps +/// than on real hardware due to QEMU's abstractions. +#[cfg(feature = "test_build")] +pub fn qemu_bring_up_console() { + use crate::cpu; + + unsafe { + instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); + console::register_console(PL011_UART.assume_init_ref()); + }; +} diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi/exception.rs b/20_timer_callbacks/kernel/src/bsp/raspberrypi/exception.rs new file mode 100644 index 000000000..a9eaa6ac4 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/20_timer_callbacks/kernel/src/bsp/raspberrypi/exception/asynchronous.rs new file mode 100644 index 000000000..82935adbe --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +/// The IRQ map. +#[cfg(feature = "bsp_rpi3")] +pub mod irq_map { + use super::bsp::device_driver::{IRQNumber, LocalIRQ, PeripheralIRQ}; + + /// The non-secure physical timer IRQ number. + pub const ARM_NS_PHYSICAL_TIMER: IRQNumber = IRQNumber::Local(LocalIRQ::new(1)); + + pub(in crate::bsp) const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +/// The IRQ map. +#[cfg(feature = "bsp_rpi4")] +pub mod irq_map { + use super::bsp::device_driver::IRQNumber; + + /// The non-secure physical timer IRQ number. + pub const ARM_NS_PHYSICAL_TIMER: IRQNumber = IRQNumber::new(30); + + pub(in crate::bsp) const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi/kernel.ld b/20_timer_callbacks/kernel/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..2408b63cd --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,134 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2022 Andre Richter + */ + +INCLUDE kernel_virt_addr_space_size.ld; + +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + +/* The kernel's virtual address range will be: + * + * [END_ADDRESS_INCLUSIVE, START_ADDRESS] + * [u64::MAX , (u64::MAX - __kernel_virt_addr_space_size) + 1] + */ +__kernel_virt_start_addr = ((0xffffffffffffffff - __kernel_virt_addr_space_size) + 1); + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); + segment_heap PT_LOAD FLAGS(6); + segment_boot_core_stack PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __kernel_virt_start_addr; + + ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + __code_start = .; + .text : AT(__rpi_phys_binary_load_addr) + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + .kernel_symbols : ALIGN(8) { + __kernel_symbols_start = .; + . += 32 * 1024; + } :segment_code + + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + __data_start = .; + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + + /*********************************************************************************************** + * Heap + ***********************************************************************************************/ + __heap_start = .; + .heap (NOLOAD) : + { + . += 16 * 1024 * 1024; + } :segment_heap + __heap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "Heap is not page aligned") + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + + /*********************************************************************************************** + * Guard Page + ***********************************************************************************************/ + . += PAGE_SIZE; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) + { + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld b/20_timer_callbacks/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld new file mode 100644 index 000000000..c5d58c30a --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld @@ -0,0 +1 @@ +__kernel_virt_addr_space_size = 1024 * 1024 * 1024 diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi/memory.rs b/20_timer_callbacks/kernel/src/bsp/raspberrypi/memory.rs new file mode 100644 index 000000000..f8c9b6a1a --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,254 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | .kernel_symbols | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | heap_start == data_end_exclusive +//! | .heap | +//! | | +//! +---------------------------------------+ +//! | | heap_end_exclusive +//! | | +//! +//! +//! +//! +//! +//! The virtual memory layout is as follows: +//! +//! +---------------------------------------+ +//! | | code_start @ __kernel_virt_start_addr +//! | .text | +//! | .rodata | +//! | .got | +//! | .kernel_symbols | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | heap_start == data_end_exclusive +//! | .heap | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_start == heap_end_exclusive +//! | VA region for MMIO remapping | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_end_exclusive +//! | Unmapped guard page | +//! | | +//! +---------------------------------------+ +//! | | boot_core_stack_start +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | boot_core_stack_end_exclusive +//! | | +pub mod mmu; + +use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; + + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + + static __heap_start: UnsafeCell<()>; + static __heap_end_exclusive: UnsafeCell<()>; + + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + + static __boot_core_stack_start: UnsafeCell<()>; + static __boot_core_stack_end_exclusive: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + use super::*; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); + pub const PERIPHERAL_IC_SIZE: usize = 0x24; + + pub const GPIO_START: Address = Address::new(0x3F20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const LOCAL_IC_START: Address = Address::new(0x4000_0000); + pub const LOCAL_IC_SIZE: usize = 0x100; + + pub const END: Address = Address::new(0x4001_0000); + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const GPIO_START: Address = Address::new(0xFE20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0xFE20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const GICD_START: Address = Address::new(0xFF84_1000); + pub const GICD_SIZE: usize = 0x824; + + pub const GICC_START: Address = Address::new(0xFF84_2000); + pub const GICC_SIZE: usize = 0x14; + + pub const END: Address = Address::new(0xFF85_0000); + } + + pub const END: Address = mmio::END; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_code_start() -> PageAddress { + PageAddress::from(unsafe { __code_start.get() as usize }) +} + +/// Size of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_size() -> usize { + unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } +} + +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { + PageAddress::from(unsafe { __data_start.get() as usize }) +} + +/// Size of the data segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn data_size() -> usize { + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } +} + +/// Start page address of the heap segment. +#[inline(always)] +fn virt_heap_start() -> PageAddress { + PageAddress::from(unsafe { __heap_start.get() as usize }) +} + +/// Size of the heap segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn heap_size() -> usize { + unsafe { (__heap_end_exclusive.get() as usize) - (__heap_start.get() as usize) } +} + +/// Start page address of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_mmio_remap_start() -> PageAddress { + PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) +} + +/// Size of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn mmio_remap_size() -> usize { + unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } +} + +/// Start page address of the boot core's stack. +#[inline(always)] +fn virt_boot_core_stack_start() -> PageAddress { + PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) +} + +/// Size of the boot core's stack. +#[inline(always)] +fn boot_core_stack_size() -> usize { + unsafe { + (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Exclusive end address of the physical address space. +#[inline(always)] +pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { + PageAddress::from(map::END) +} diff --git a/20_timer_callbacks/kernel/src/bsp/raspberrypi/memory/mmu.rs b/20_timer_callbacks/kernel/src/bsp/raspberrypi/memory/mmu.rs new file mode 100644 index 000000000..ef52e3686 --- /dev/null +++ b/20_timer_callbacks/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use crate::{ + memory::{ + mmu::{ + self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, + MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type KernelTranslationTable = + ::TableStartFromTop; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to +/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. +pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + +/// The kernel's virtual address space defined by this BSP. +pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// It is mandatory that InitStateLock is transparent. +/// +/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. +/// There is a unit tests that checks this porperty. +#[link_section = ".data"] +#[no_mangle] +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new_for_precompute()); + +/// This value is needed during early boot for MMU setup. +/// +/// This will be patched to the correct value by the "translation table tool" after linking. This +/// given value here is just a dummy. +#[link_section = ".text._start_arguments"] +#[no_mangle] +static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This is a hack for retrieving the value for the kernel's virtual address space size as a +/// constant from a common place, since it is needed as a compile-time/link-time constant in both, +/// the linker script and the Rust sources. +#[allow(clippy::needless_late_init)] +const fn kernel_virt_addr_space_size() -> usize { + let __kernel_virt_addr_space_size; + + include!("../kernel_virt_addr_space_size.ld"); + + __kernel_virt_addr_space_size +} + +/// Helper function for calculating the number of pages the given parameter spans. +const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); + assert!(size % KernelGranule::SIZE == 0); + + size >> KernelGranule::SHIFT +} + +/// The data pages of the kernel binary. +fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); + + let start_page_addr = super::virt_data_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +// There is no reason to expect the following conversions to fail, since they were generated offline +// by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. +fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { + let phys_start_page_addr = + generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) + .unwrap(); + + let phys_end_exclusive_page_addr = phys_start_page_addr + .checked_offset(virt_region.num_pages() as isize) + .unwrap(); + + MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) +} + +fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { + generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The code pages of the kernel binary. +pub fn virt_code_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::code_size()); + + let start_page_addr = super::virt_code_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The heap pages. +pub fn virt_heap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::heap_size()); + + let start_page_addr = super::virt_heap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The boot core stack pages. +pub fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); + + let start_page_addr = super::virt_boot_core_stack_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} + +/// The MMIO remap pages. +pub fn virt_mmio_remap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::mmio_remap_size()); + + let start_page_addr = super::virt_mmio_remap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Add mapping records for the kernel binary. +/// +/// The actual translation table entries for the kernel binary are generated using the offline +/// `translation table tool` and patched into the kernel binary. This function just adds the mapping +/// record entries. +pub fn kernel_add_mapping_records_for_precomputed() { + let virt_code_region = virt_code_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel code and RO data", + &virt_code_region, + &kernel_virt_to_phys_region(virt_code_region), + &kernel_page_attributes(virt_code_region.start_page_addr()), + ); + + let virt_data_region = virt_data_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel data and bss", + &virt_data_region, + &kernel_virt_to_phys_region(virt_data_region), + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); + + let virt_heap_region = virt_heap_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel heap", + &virt_heap_region, + &kernel_virt_to_phys_region(virt_heap_region), + &kernel_page_attributes(virt_heap_region.start_page_addr()), + ); + + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", + &virt_boot_core_stack_region, + &kernel_virt_to_phys_region(virt_boot_core_stack_region), + &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), + ); +} diff --git a/20_timer_callbacks/kernel/src/common.rs b/20_timer_callbacks/kernel/src/common.rs new file mode 100644 index 000000000..2ad7e4c1e --- /dev/null +++ b/20_timer_callbacks/kernel/src/common.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Check if a value is aligned to a given size. +#[inline(always)] +pub const fn is_aligned(value: usize, alignment: usize) -> bool { + assert!(alignment.is_power_of_two()); + + (value & (alignment - 1)) == 0 +} + +/// Align down. +#[inline(always)] +pub const fn align_down(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + value & !(alignment - 1) +} + +/// Align up. +#[inline(always)] +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + (value + alignment - 1) & !(alignment - 1) +} + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff --git a/20_timer_callbacks/kernel/src/console.rs b/20_timer_callbacks/kernel/src/console.rs new file mode 100644 index 000000000..5efa9395b --- /dev/null +++ b/20_timer_callbacks/kernel/src/console.rs @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +mod buffer_console; + +use crate::synchronization; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + use core::fmt; + + /// Console write functions. + pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + + /// Write a slice of characters. + fn write_array(&self, a: &[char]); + + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&buffer_console::BUFFER_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.write(|con| *con = new_console); + + static FIRST_SWITCH: InitStateLock = InitStateLock::new(true); + FIRST_SWITCH.write(|first| { + if *first { + *first = false; + + buffer_console::BUFFER_CONSOLE.dump(); + } + }); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.read(|con| *con) +} diff --git a/20_timer_callbacks/kernel/src/console/buffer_console.rs b/20_timer_callbacks/kernel/src/console/buffer_console.rs new file mode 100644 index 000000000..05903e7cf --- /dev/null +++ b/20_timer_callbacks/kernel/src/console/buffer_console.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A console that buffers input during the init phase. + +use super::interface; +use crate::{console, info, synchronization, synchronization::InitStateLock}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const BUF_SIZE: usize = 1024 * 64; + +pub struct BufferConsoleInner { + buf: [char; BUF_SIZE], + write_ptr: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct BufferConsole { + inner: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static BUFFER_CONSOLE: BufferConsole = BufferConsole { + inner: InitStateLock::new(BufferConsoleInner { + // Use the null character, so this lands in .bss and does not waste space in the binary. + buf: ['\0'; BUF_SIZE], + write_ptr: 0, + }), +}; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl BufferConsoleInner { + fn write_char(&mut self, c: char) { + if self.write_ptr < (BUF_SIZE - 1) { + self.buf[self.write_ptr] = c; + self.write_ptr += 1; + } + } +} + +impl fmt::Write for BufferConsoleInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +impl BufferConsole { + /// Dump the buffer. + /// + /// # Invariant + /// + /// It is expected that this is only called when self != crate::console::console(). + pub fn dump(&self) { + self.inner.read(|inner| { + console::console().write_array(&inner.buf[0..inner.write_ptr]); + + if inner.write_ptr == (BUF_SIZE - 1) { + info!("Pre-UART buffer overflowed"); + } else if inner.write_ptr > 0 { + info!("End of pre-UART buffer") + } + }); + } +} + +impl interface::Write for BufferConsole { + fn write_char(&self, c: char) { + self.inner.write(|inner| inner.write_char(c)); + } + + fn write_array(&self, _a: &[char]) {} + + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result { + self.inner.write(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) {} +} + +impl interface::Read for BufferConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for BufferConsole {} +impl interface::All for BufferConsole {} diff --git a/20_timer_callbacks/kernel/src/cpu.rs b/20_timer_callbacks/kernel/src/cpu.rs new file mode 100644 index 000000000..8716a918b --- /dev/null +++ b/20_timer_callbacks/kernel/src/cpu.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Processor code. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/cpu.rs"] +mod arch_cpu; + +mod boot; + +pub mod smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "test_build")] +pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; diff --git a/20_timer_callbacks/kernel/src/cpu/boot.rs b/20_timer_callbacks/kernel/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/20_timer_callbacks/kernel/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/20_timer_callbacks/kernel/src/cpu/smp.rs b/20_timer_callbacks/kernel/src/cpu/smp.rs new file mode 100644 index 000000000..de612d589 --- /dev/null +++ b/20_timer_callbacks/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff --git a/20_timer_callbacks/kernel/src/driver.rs b/20_timer_callbacks/kernel/src/driver.rs new file mode 100644 index 000000000..88b41b818 --- /dev/null +++ b/20_timer_callbacks/kernel/src/driver.rs @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, +}; +use alloc::vec::Vec; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager +where + T: 'static, +{ + descriptors: InitStateLock>>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + irq_number: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + irq_number, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager +where + T: fmt::Display, +{ + /// Create an instance. + pub const fn new() -> Self { + Self { + descriptors: InitStateLock::new(Vec::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.descriptors + .write(|descriptors| descriptors.push(descriptor)); + } + + /// Fully initialize all drivers and their interrupts handlers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers_and_irqs(&self) { + self.descriptors.read(|descriptors| { + for descriptor in descriptors { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + } + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + for descriptor in descriptors { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + } + }) + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + self.descriptors.read(|descriptors| { + for (i, desc) in descriptors.iter().enumerate() { + info!(" {}. {}", i + 1, desc.device_driver.compatible()); + } + }); + } +} diff --git a/20_timer_callbacks/kernel/src/exception.rs b/20_timer_callbacks/kernel/src/exception.rs new file mode 100644 index 000000000..3d5f219f3 --- /dev/null +++ b/20_timer_callbacks/kernel/src/exception.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::{current_privilege_level, handling_init}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Libkernel unit tests must execute in kernel mode. + #[kernel_test] + fn test_runner_executes_in_kernel_mode() { + let (level, _) = current_privilege_level(); + + assert!(level == PrivilegeLevel::Kernel) + } +} diff --git a/20_timer_callbacks/kernel/src/exception/asynchronous.rs b/20_timer_callbacks/kernel/src/exception/asynchronous.rs new file mode 100644 index 000000000..2c874dd60 --- /dev/null +++ b/20_timer_callbacks/kernel/src/exception/asynchronous.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff --git a/20_timer_callbacks/kernel/src/exception/asynchronous/null_irq_manager.rs b/20_timer_callbacks/kernel/src/exception/asynchronous/null_irq_manager.rs new file mode 100644 index 000000000..38919ffe4 --- /dev/null +++ b/20_timer_callbacks/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff --git a/20_timer_callbacks/kernel/src/lib.rs b/20_timer_callbacks/kernel/src/lib.rs new file mode 100644 index 000000000..317bcc727 --- /dev/null +++ b/20_timer_callbacks/kernel/src/lib.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` library. +//! +//! Used to compose the final kernel binary. +//! +//! # Code organization and architecture +//! +//! The code is divided into different *modules*, each representing a typical **subsystem** of the +//! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, +//! `src/memory.rs` contains code that is concerned with all things memory management. +//! +//! ## Visibility of processor architecture code +//! +//! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target +//! processor architecture. For each supported processor architecture, there exists a subfolder in +//! `src/_arch`, for example, `src/_arch/aarch64`. +//! +//! The architecture folders mirror the subsystem modules laid out in `src`. For example, +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` +//! +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. +//! +//! ## BSP code +//! +//! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains +//! target board specific definitions and functions. These are things such as the board's memory map +//! or instances of drivers for devices that are featured on the respective board. +//! +//! Just like processor architecture code, the `BSP` code's module structure tries to mirror the +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. +//! +//! ## Kernel interfaces +//! +//! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target +//! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of +//! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` +//! code to play nicely with any of the two without much hassle. +//! +//! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, +//! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined +//! in the respective subsystem module and help to enforce the idiom of *program to an interface, +//! not an implementation*. For example, there will be a common IRQ handling interface which the two +//! different interrupt controller `drivers` of both Raspberrys will implement, and only export the +//! interface to the rest of the `kernel`. +//! +//! ``` +//! +-------------------+ +//! | Interface (Trait) | +//! | | +//! +--+-------------+--+ +//! ^ ^ +//! | | +//! | | +//! +----------+--+ +--+----------+ +//! | kernel code | | bsp code | +//! | | | arch code | +//! +-------------+ +-------------+ +//! ``` +//! +//! # Summary +//! +//! For a logical `kernel` subsystem, corresponding code can be distributed over several physical +//! locations. Here is an example for the **memory** subsystem: +//! +//! - `src/memory.rs` and `src/memory/**/*` +//! - Common code that is agnostic of target processor architecture and `BSP` characteristics. +//! - Example: A function to zero a chunk of memory. +//! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. +//! - Example: An `MMU` interface that defines `MMU` function prototypes. +//! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` +//! - `BSP` specific code. +//! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). +//! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` +//! - Processor architecture specific code. +//! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor +//! architecture. +//! +//! From a namespace perspective, **memory** subsystem code lives in: +//! +//! - `crate::memory::*` +//! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + +#![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] +#![feature(alloc_error_handler)] +#![feature(asm_const)] +#![feature(const_option)] +#![feature(core_intrinsics)] +#![feature(format_args_nl)] +#![feature(generic_const_exprs)] +#![feature(int_roundings)] +#![feature(is_sorted)] +#![feature(linkage)] +#![feature(nonzero_min_max)] +#![feature(panic_info_message)] +#![feature(step_trait)] +#![feature(trait_alias)] +#![feature(unchecked_math)] +#![no_std] +// Testing +#![cfg_attr(test, no_main)] +#![feature(custom_test_frameworks)] +#![reexport_test_harness_main = "test_main"] +#![test_runner(crate::test_runner)] + +extern crate alloc; + +mod panic_wait; +mod synchronization; + +pub mod backtrace; +pub mod bsp; +pub mod common; +pub mod console; +pub mod cpu; +pub mod driver; +pub mod exception; +pub mod memory; +pub mod print; +pub mod state; +pub mod symbols; +pub mod time; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Version string. +pub fn version() -> &'static str { + concat!( + env!("CARGO_PKG_NAME"), + " version ", + env!("CARGO_PKG_VERSION") + ) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +/// The default runner for unit tests. +pub fn test_runner(tests: &[&test_types::UnitTest]) { + // This line will be printed as the test header. + println!("Running {} tests", tests.len()); + + for (i, test) in tests.iter().enumerate() { + print!("{:>3}. {:.<58}", i + 1, test.name); + + // Run the actual test. + (test.test_func)(); + + // Failed tests call panic!(). Execution reaches here only if the test has passed. + println!("[ok]") + } +} + +/// The `kernel_init()` for unit tests. +#[cfg(test)] +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + test_main(); + + cpu::qemu_exit_success() +} diff --git a/20_timer_callbacks/kernel/src/main.rs b/20_timer_callbacks/kernel/src/main.rs new file mode 100644 index 000000000..249b27180 --- /dev/null +++ b/20_timer_callbacks/kernel/src/main.rs @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +// Rust embedded logo for `make doc`. +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] + +//! The `kernel` binary. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +extern crate alloc; + +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; + +/// Early init code. +/// +/// When this code runs, virtual memory is already enabled. +/// +/// # Safety +/// +/// - Only a single core must be active and running this function. +/// - Printing will not work until the respective driver's MMIO is remapped. +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + + // Initialize the timer subsystem. + if let Err(x) = time::init() { + panic!("Error initializing timer subsystem: {}", x); + } + + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); + + bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); + + // Transition from unsafe to safe. + kernel_main() +} + +/// The main function running after the early init. +fn kernel_main() -> ! { + use alloc::boxed::Box; + use core::time::Duration; + + info!("{}", libkernel::version()); + info!("Booting on: {}", bsp::board_name()); + + info!("MMU online:"); + memory::mmu::kernel_print_mappings(); + + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); + + info!("Kernel heap:"); + memory::heap_alloc::kernel_heap_allocator().print_usage(); + + time::time_manager().set_timeout_once(Duration::from_secs(5), Box::new(|| info!("Once 5"))); + time::time_manager().set_timeout_once(Duration::from_secs(3), Box::new(|| info!("Once 2"))); + time::time_manager() + .set_timeout_periodic(Duration::from_secs(1), Box::new(|| info!("Periodic 1 sec"))); + + info!("Echoing input now"); + cpu::wait_forever(); +} diff --git a/20_timer_callbacks/kernel/src/memory.rs b/20_timer_callbacks/kernel/src/memory.rs new file mode 100644 index 000000000..bc6113366 --- /dev/null +++ b/20_timer_callbacks/kernel/src/memory.rs @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod heap_alloc; +pub mod mmu; + +use crate::{bsp, common}; +use core::{ + fmt, + marker::PhantomData, + ops::{Add, Sub}, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Physical {} + +/// Zero-sized type to mark a virtual address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl AddressType for Physical {} +impl AddressType for Virtual {} + +impl Address { + /// Create an instance. + pub const fn new(value: usize) -> Self { + Self { + value, + _address_type: PhantomData, + } + } + + /// Convert to usize. + pub const fn as_usize(self) -> usize { + self.value + } + + /// Align down to page size. + #[must_use] + pub const fn align_down_page(self) -> Self { + let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Align up to page size. + #[must_use] + pub const fn align_up_page(self) -> Self { + let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Checks if the address is page aligned. + pub const fn is_page_aligned(&self) -> bool { + common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) + } + + /// Return the address' offset into the corresponding page. + pub const fn offset_into_page(&self) -> usize { + self.value & bsp::memory::mmu::KernelGranule::MASK + } +} + +impl Add for Address { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: usize) -> Self::Output { + match self.value.checked_add(rhs) { + None => panic!("Overflow on Address::add"), + Some(x) => Self::new(x), + } + } +} + +impl Sub for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: usize) -> Self::Output { + match self.value.checked_sub(rhs) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl Sub> for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Address) -> Self::Output { + match self.value.checked_sub(rhs.value) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl Address { + /// Checks if the address is part of the boot core stack region. + pub fn is_valid_stack_addr(&self) -> bool { + bsp::memory::mmu::virt_boot_core_stack_region().contains(*self) + } + + /// Checks if the address is part of the kernel code region. + pub fn is_valid_code_addr(&self) -> bool { + bsp::memory::mmu::virt_code_region().contains(*self) + } +} + +impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q3: u8 = ((self.value >> 32) & 0xff) as u8; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:02x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q4: u16 = ((self.value >> 48) & 0xffff) as u16; + let q3: u16 = ((self.value >> 32) & 0xffff) as u16; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:04x}_", q4)?; + write!(f, "{:04x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); + heap_alloc::kernel_init_heap_allocator(); +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of [Address] methods. + #[kernel_test] + fn address_type_method_sanity() { + let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); + + assert_eq!( + addr.align_down_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE + ); + + assert_eq!( + addr.align_up_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + + assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} diff --git a/20_timer_callbacks/kernel/src/memory/heap_alloc.rs b/20_timer_callbacks/kernel/src/memory/heap_alloc.rs new file mode 100644 index 000000000..cf4298fa4 --- /dev/null +++ b/20_timer_callbacks/kernel/src/memory/heap_alloc.rs @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Heap allocation. + +use crate::{ + backtrace, bsp, common, debug, info, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, + warn, +}; +use alloc::alloc::{GlobalAlloc, Layout}; +use core::sync::atomic::{AtomicBool, Ordering}; +use linked_list_allocator::Heap as LinkedListHeap; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A heap allocator that can be lazyily initialized. +pub struct HeapAllocator { + inner: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +#[global_allocator] +static KERNEL_HEAP_ALLOCATOR: HeapAllocator = HeapAllocator::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +#[inline(always)] +fn debug_print_alloc_dealloc(operation: &'static str, ptr: *mut u8, layout: Layout) { + let size = layout.size(); + let (size_h, size_unit) = common::size_human_readable_ceil(size); + let addr = Address::::new(ptr as usize); + + debug!( + "Kernel Heap: {}\n \ + Size: {:#x} ({} {})\n \ + Start: {}\n \ + End excl: {}\n\n \ + {}", + operation, + size, + size_h, + size_unit, + addr, + addr + size, + backtrace::Backtrace + ); +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +#[alloc_error_handler] +fn alloc_error_handler(layout: Layout) -> ! { + panic!("Allocation error: {:?}", layout) +} + +/// Return a reference to the kernel's heap allocator. +pub fn kernel_heap_allocator() -> &'static HeapAllocator { + &KERNEL_HEAP_ALLOCATOR +} + +impl HeapAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: IRQSafeNullLock::new(LinkedListHeap::empty()), + } + } + + /// Print the current heap usage. + pub fn print_usage(&self) { + let (used, free) = KERNEL_HEAP_ALLOCATOR + .inner + .lock(|inner| (inner.used(), inner.free())); + + if used >= 1024 { + let (used_h, used_unit) = common::size_human_readable_ceil(used); + info!(" Used: {} Byte ({} {})", used, used_h, used_unit); + } else { + info!(" Used: {} Byte", used); + } + + if free >= 1024 { + let (free_h, free_unit) = common::size_human_readable_ceil(free); + info!(" Free: {} Byte ({} {})", free, free_h, free_unit); + } else { + info!(" Free: {} Byte", free); + } + } +} + +unsafe impl GlobalAlloc for HeapAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let result = KERNEL_HEAP_ALLOCATOR + .inner + .lock(|inner| inner.allocate_first_fit(layout).ok()); + + match result { + None => core::ptr::null_mut(), + Some(allocation) => { + let ptr = allocation.as_ptr(); + + debug_print_alloc_dealloc("Allocation", ptr, layout); + + ptr + } + } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + KERNEL_HEAP_ALLOCATOR + .inner + .lock(|inner| inner.deallocate(core::ptr::NonNull::new_unchecked(ptr), layout)); + + debug_print_alloc_dealloc("Free", ptr, layout); + } +} + +/// Query the BSP for the heap region and initialize the kernel's heap allocator with it. +pub fn kernel_init_heap_allocator() { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + warn!("Already initialized"); + return; + } + + let region = bsp::memory::mmu::virt_heap_region(); + + KERNEL_HEAP_ALLOCATOR.inner.lock(|inner| unsafe { + inner.init(region.start_addr().as_usize() as *mut u8, region.size()) + }); + + INIT_DONE.store(true, Ordering::Relaxed); +} diff --git a/20_timer_callbacks/kernel/src/memory/mmu.rs b/20_timer_callbacks/kernel/src/memory/mmu.rs new file mode 100644 index 000000000..abe3b1813 --- /dev/null +++ b/20_timer_callbacks/kernel/src/memory/mmu.rs @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod mapping_record; +mod page_alloc; +mod translation_table; +mod types; + +use crate::{ + bsp, + memory::{Address, Physical, Virtual}, + synchronization::{self, interface::Mutex}, +}; +use core::{fmt, num::NonZeroUsize}; + +pub use types::*; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Turns on the MMU for the first time and enables data and instruction caching. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] + type TableStartFromTop; + + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +use interface::MMU; +use synchronization::interface::ReadWriteEx; +use translation_table::interface::TranslationTable; + +/// Map a region in the kernel's translation tables. +/// +/// No input checks done, input is passed through to the architectural implementation. +/// +/// # Safety +/// +/// - See `map_at()`. +/// - Does not prevent aliasing. +unsafe fn kernel_map_at_unchecked( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; + + kernel_add_mapping_record(name, virt_region, phys_region, attr); + + Ok(()) +} + +/// Try to translate a kernel virtual address to a physical address. +/// +/// Will only succeed if there exists a valid mapping for the input address. +fn try_kernel_virt_addr_to_phys_addr( + virt_addr: Address, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's mask. + pub const MASK: usize = Self::SIZE - 1; + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +pub fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Add an entry to the mapping info record. +pub fn kernel_add_mapping_record( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) { + mapping_record::kernel_add(name, virt_region, phys_region, attr); +} + +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +/// +/// # Safety +/// +/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + let phys_region = MemoryRegion::from(*mmio_descriptor); + let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); + + // Check if an identical region has been mapped for another driver. If so, reuse it. + let virt_addr = if let Some(addr) = + mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) + { + addr + // Otherwise, allocate a new region and map it. + } else { + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, + }; + + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + virt_region.start_addr() + }; + + Ok(virt_addr + offset_into_start_page) +} + +/// Try to translate a kernel virtual page address to a physical page address. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_virt_page_addr_to_phys_page_addr( + virt_page_addr: PageAddress, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) +} + +/// Try to get the attributes of a kernel page. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_page_attributes( + virt_page_addr: PageAddress, +) -> Result { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_page_attributes(virt_page_addr)) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() +} + +/// Enable the MMU and data + instruction caching. +/// +/// # Safety +/// +/// - Crucial function during kernel init. Changes the the complete memory view of the processor. +#[inline(always)] +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) +} diff --git a/20_timer_callbacks/kernel/src/memory/mmu/mapping_record.rs b/20_timer_callbacks/kernel/src/memory/mmu/mapping_record.rs new file mode 100644 index 000000000..9c17258d1 --- /dev/null +++ b/20_timer_callbacks/kernel/src/memory/mmu/mapping_record.rs @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + +use super::{ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock}; +use alloc::{vec, vec::Vec}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Type describing a virtual memory mapping. +#[allow(missing_docs)] +struct MappingRecordEntry { + pub users: Vec<&'static str>, + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, + pub attribute_fields: AttributeFields, +} + +struct MappingRecord { + inner: Vec, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MAPPING_RECORD: InitStateLock = + InitStateLock::new(MappingRecord::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl MappingRecordEntry { + pub fn new( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Self { + Self { + users: vec![name], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), + attribute_fields: *attr, + } + } + + pub fn add_user(&mut self, user: &'static str) { + self.users.push(user); + } +} + +impl MappingRecord { + pub const fn new() -> Self { + Self { inner: Vec::new() } + } + + fn sort(&mut self) { + if !self.inner.is_sorted_by_key(|item| item.virt_start_addr) { + self.inner.sort_unstable_by_key(|item| item.virt_start_addr) + } + } + + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { + return false; + } + + if x.num_pages != phys_region.num_pages() { + return false; + } + + true + }) + } + + pub fn add( + &mut self, + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) { + self.inner.push(MappingRecordEntry::new( + name, + virt_region, + phys_region, + attr, + )); + + self.sort(); + } + + pub fn print(&self) { + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", + "Virtual", "Physical", "Size", "Attr", "Entity" + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + + for i in self.inner.iter() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match i.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if i.attribute_fields.execute_never { + "XN" + } else { + "X" + }; + + info!( + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, + phys_end_inclusive, + size, + unit, + attr, + acc_p, + xn, + i.users[0] + ); + + for k in &i.users[1..] { + info!( + " | {}", + k + ); + } + } + + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +/// Add an entry to the mapping info record. +pub fn kernel_add( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) +} + +pub fn kernel_find_and_insert_mmio_duplicate( + mmio_descriptor: &MMIODescriptor, + new_user: &'static str, +) -> Option> { + let phys_region: MemoryRegion = (*mmio_descriptor).into(); + + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + + dup.add_user(new_user); + + Some(dup.virt_start_addr) + }) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print() { + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} diff --git a/20_timer_callbacks/kernel/src/memory/mmu/page_alloc.rs b/20_timer_callbacks/kernel/src/memory/mmu/page_alloc.rs new file mode 100644 index 000000000..344afd200 --- /dev/null +++ b/20_timer_callbacks/kernel/src/memory/mmu/page_alloc.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Page allocation. + +use super::MemoryRegion; +use crate::{ + memory::{AddressType, Virtual}, + synchronization::IRQSafeNullLock, + warn, +}; +use core::num::NonZeroUsize; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A page allocator that can be lazyily initialized. +pub struct PageAllocator { + pool: Option>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = + IRQSafeNullLock::new(PageAllocator::new()); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's MMIO virtual address allocator. +pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { + &KERNEL_MMIO_VA_ALLOCATOR +} + +impl PageAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { pool: None } + } + + /// Initialize the allocator. + pub fn init(&mut self, pool: MemoryRegion) { + if self.pool.is_some() { + warn!("Already initialized"); + return; + } + + self.pool = Some(pool); + } + + /// Allocate a number of pages. + pub fn alloc( + &mut self, + num_requested_pages: NonZeroUsize, + ) -> Result, &'static str> { + if self.pool.is_none() { + return Err("Allocator not initialized"); + } + + self.pool + .as_mut() + .unwrap() + .take_first_n_pages(num_requested_pages) + } +} diff --git a/20_timer_callbacks/kernel/src/memory/mmu/translation_table.rs b/20_timer_callbacks/kernel/src/memory/mmu/translation_table.rs new file mode 100644 index 000000000..341ffc5c8 --- /dev/null +++ b/20_timer_callbacks/kernel/src/memory/mmu/translation_table.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +use super::{AttributeFields, MemoryRegion}; +use crate::memory::{Address, Physical, Virtual}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +#[cfg(target_arch = "aarch64")] +pub use arch_translation_table::FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Translation table interfaces. +pub mod interface { + use crate::memory::mmu::PageAddress; + + use super::*; + + /// Translation table operations. + pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self) -> Result<(), &'static str>; + + /// Map the given virtual memory region to the given physical memory region. + /// + /// # Safety + /// + /// - Using wrong attributes can cause multiple issues of different nature in the system. + /// - It is not required that the architectural implementation prevents aliasing. That is, + /// mapping to the same physical memory using multiple virtual addresses, which would + /// break Rust's ownership assumptions. This should be protected against in the kernel's + /// generic MMU code. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; + + /// Try to translate a virtual page address to a physical page address. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str>; + + /// Try to get the attributes of a page. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result; + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str>; + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use arch_translation_table::MinSizeTranslationTable; + use interface::TranslationTable; + use test_macros::kernel_test; + + /// Sanity checks for the TranslationTable implementation. + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. + let mut tables = MinSizeTranslationTable::new_for_runtime(); + + assert_eq!(tables.init(), Ok(())); + + let virt_end_exclusive_page_addr: PageAddress = PageAddress::MAX; + let virt_start_page_addr: PageAddress = + virt_end_exclusive_page_addr.checked_offset(-5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + + let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + + assert_eq!( + tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), + Ok(phys_start_page_addr) + ); + + assert_eq!( + tables.try_page_attributes(virt_start_page_addr.checked_offset(-1).unwrap()), + Err("Page marked invalid") + ); + + assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); + + let virt_addr = virt_start_page_addr.into_inner() + 0x100; + let phys_addr = phys_start_page_addr.into_inner() + 0x100; + assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); + } +} diff --git a/20_timer_callbacks/kernel/src/memory/mmu/types.rs b/20_timer_callbacks/kernel/src/memory/mmu/types.rs new file mode 100644 index 000000000..f6ac8d598 --- /dev/null +++ b/20_timer_callbacks/kernel/src/memory/mmu/types.rs @@ -0,0 +1,378 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + +use crate::{ + bsp, common, + memory::{Address, AddressType, Physical}, +}; +use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct PageAddress { + inner: Address, +} + +/// A type that describes a region of memory in quantities of pages. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// An MMIO descriptor for use in device drivers. +#[derive(Copy, Clone)] +pub struct MMIODescriptor { + start_addr: Address, + end_addr_exclusive: Address, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------ +// PageAddress +//------------------------------------------------------------------------------ +impl PageAddress { + /// The largest value that can be represented by this type. + pub const MAX: Self = PageAddress { + inner: Address::new(usize::MAX).align_down_page(), + }; + + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + } + + /// Calculates the offset from the page address. + /// + /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * + /// page_size`. + pub fn checked_offset(self, count: isize) -> Option { + if count == 0 { + return Some(self); + } + + let delta = count + .unsigned_abs() + .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; + let result = if count.is_positive() { + self.inner.as_usize().checked_add(delta)? + } else { + self.inner.as_usize().checked_sub(delta)? + }; + + Some(Self { + inner: Address::new(result), + }) + } +} + +impl From for PageAddress { + fn from(addr: usize) -> Self { + assert!( + common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), + "Input usize not page aligned" + ); + + Self { + inner: Address::new(addr), + } + } +} + +impl From> for PageAddress { + fn from(addr: Address) -> Self { + assert!(addr.is_page_aligned(), "Input Address not page aligned"); + + Self { inner: addr } + } +} + +impl Step for PageAddress { + fn steps_between(start: &Self, end: &Self) -> Option { + if start > end { + return None; + } + + // Since start <= end, do unchecked arithmetic. + Some( + (end.inner.as_usize() - start.inner.as_usize()) + >> bsp::memory::mmu::KernelGranule::SHIFT, + ) + } + + fn forward_checked(start: Self, count: usize) -> Option { + start.checked_offset(count as isize) + } + + fn backward_checked(start: Self, count: usize) -> Option { + start.checked_offset(-(count as isize)) + } +} + +//------------------------------------------------------------------------------ +// MemoryRegion +//------------------------------------------------------------------------------ +impl MemoryRegion { + /// Create an instance. + pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { + assert!(start <= end_exclusive); + + Self { + start, + end_exclusive, + } + } + + fn as_range(&self) -> Range> { + self.into_iter() + } + + /// Returns the start page address. + pub fn start_page_addr(&self) -> PageAddress { + self.start + } + + /// Returns the start address. + pub fn start_addr(&self) -> Address { + self.start.into_inner() + } + + /// Returns the exclusive end page address. + pub fn end_exclusive_page_addr(&self) -> PageAddress { + self.end_exclusive + } + + /// Returns the exclusive end page address. + pub fn end_inclusive_page_addr(&self) -> PageAddress { + self.end_exclusive.checked_offset(-1).unwrap() + } + + /// Checks if self contains an address. + pub fn contains(&self, addr: Address) -> bool { + let page_addr = PageAddress::from(addr.align_down_page()); + self.as_range().contains(&page_addr) + } + + /// Checks if there is an overlap with another memory region. + pub fn overlaps(&self, other_region: &Self) -> bool { + let self_range = self.as_range(); + + self_range.contains(&other_region.start_page_addr()) + || self_range.contains(&other_region.end_inclusive_page_addr()) + } + + /// Returns the number of pages contained in this region. + pub fn num_pages(&self) -> usize { + PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() + } + + /// Returns the size in bytes of this region. + pub fn size(&self) -> usize { + // Invariant: start <= end_exclusive, so do unchecked arithmetic. + let end_exclusive = self.end_exclusive.into_inner().as_usize(); + let start = self.start.into_inner().as_usize(); + + end_exclusive - start + } + + /// Splits the MemoryRegion like: + /// + /// -------------------------------------------------------------------------------- + /// | | | | | | | | | | | | | | | | | | | + /// -------------------------------------------------------------------------------- + /// ^ ^ ^ + /// | | | + /// left_start left_end_exclusive | + /// | + /// ^ | + /// | | + /// right_start right_end_exclusive + /// + /// Left region is returned to the caller. Right region is the new region for this struct. + pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { + let count: usize = num_pages.into(); + + let left_end_exclusive = self.start.checked_offset(count as isize); + let left_end_exclusive = match left_end_exclusive { + None => return Err("Overflow while calculating left_end_exclusive"), + Some(x) => x, + }; + + if left_end_exclusive > self.end_exclusive { + return Err("Not enough free pages"); + } + + let allocation = Self { + start: self.start, + end_exclusive: left_end_exclusive, + }; + self.start = left_end_exclusive; + + Ok(allocation) + } +} + +impl IntoIterator for MemoryRegion { + type Item = PageAddress; + type IntoIter = Range; + + fn into_iter(self) -> Self::IntoIter { + Range { + start: self.start, + end: self.end_exclusive, + } + } +} + +impl From for MemoryRegion { + fn from(desc: MMIODescriptor) -> Self { + let start = PageAddress::from(desc.start_addr.align_down_page()); + let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); + + Self { + start, + end_exclusive, + } + } +} + +//------------------------------------------------------------------------------ +// MMIODescriptor +//------------------------------------------------------------------------------ + +impl MMIODescriptor { + /// Create an instance. + pub const fn new(start_addr: Address, size: usize) -> Self { + assert!(size > 0); + let end_addr_exclusive = Address::new(start_addr.as_usize() + size); + + Self { + start_addr, + end_addr_exclusive, + } + } + + /// Return the start address. + pub const fn start_addr(&self) -> Address { + self.start_addr + } + + /// Return the exclusive end address. + pub fn end_addr_exclusive(&self) -> Address { + self.end_addr_exclusive + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::Virtual; + use test_macros::kernel_test; + + /// Sanity of [PageAddress] methods. + #[kernel_test] + fn pageaddress_type_method_sanity() { + let page_addr: PageAddress = + PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); + + assert_eq!( + page_addr.checked_offset(-2), + Some(PageAddress::::from(0)) + ); + + assert_eq!( + page_addr.checked_offset(2), + Some(PageAddress::::from( + bsp::memory::mmu::KernelGranule::SIZE * 4 + )) + ); + + assert_eq!( + PageAddress::::from(0).checked_offset(0), + Some(PageAddress::::from(0)) + ); + assert_eq!(PageAddress::::from(0).checked_offset(-1), None); + + let max_page_addr = Address::::new(usize::MAX).align_down_page(); + assert_eq!( + PageAddress::::from(max_page_addr).checked_offset(1), + None + ); + + let zero = PageAddress::::from(0); + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); + } + + /// Sanity of [MemoryRegion] methods. + #[kernel_test] + fn memoryregion_type_method_sanity() { + let zero = PageAddress::::from(0); + let zero_region = MemoryRegion::new(zero, zero); + assert_eq!(zero_region.num_pages(), 0); + assert_eq!(zero_region.size(), 0); + + let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); + let one_region = MemoryRegion::new(zero, one); + assert_eq!(one_region.num_pages(), 1); + assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); + + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + let mut three_region = MemoryRegion::new(zero, three); + assert!(three_region.contains(zero.into_inner())); + assert!(!three_region.contains(three.into_inner())); + assert!(three_region.overlaps(&one_region)); + + let allocation = three_region + .take_first_n_pages(NonZeroUsize::new(2).unwrap()) + .unwrap(); + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + + for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE + ); + } + } +} diff --git a/20_timer_callbacks/kernel/src/panic_wait.rs b/20_timer_callbacks/kernel/src/panic_wait.rs new file mode 100644 index 000000000..389eb2c88 --- /dev/null +++ b/20_timer_callbacks/kernel/src/panic_wait.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! A panic handler that infinitely waits. + +use crate::{backtrace, cpu, exception, println}; +use core::panic::PanicInfo; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// The point of exit for `libkernel`. +/// +/// It is linked weakly, so that the integration tests can overload its standard behavior. +#[linkage = "weak"] +#[no_mangle] +fn _panic_exit() -> ! { + #[cfg(not(feature = "test_build"))] + { + cpu::wait_forever() + } + + #[cfg(feature = "test_build")] + { + cpu::qemu_exit_failure() + } +} + +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + _panic_exit() +} + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + backtrace::Backtrace + ); + + _panic_exit() +} diff --git a/20_timer_callbacks/kernel/src/print.rs b/20_timer_callbacks/kernel/src/print.rs new file mode 100644 index 000000000..a89f8201d --- /dev/null +++ b/20_timer_callbacks/kernel/src/print.rs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + console::console().write_fmt(args).unwrap(); +} + +/// Prints without a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); +} + +/// Prints with a newline. +/// +/// Carbon copy from +#[macro_export] +macro_rules! println { + () => ($crate::print!("\n")); + ($($arg:tt)*) => ({ + $crate::print::_print(format_args_nl!($($arg)*)); + }) +} + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Debug print, with a newline. +#[macro_export] +macro_rules! debug { + ($string:expr) => ({ + if cfg!(feature = "debug_prints") { + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("<[>D {:>3}.{:06}> ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + } + }); + ($format_string:expr, $($arg:tt)*) => ({ + if cfg!(feature = "debug_prints") { + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("3}.{:06}> ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + } + }) +} diff --git a/20_timer_callbacks/kernel/src/state.rs b/20_timer_callbacks/kernel/src/state.rs new file mode 100644 index 000000000..6d99beedb --- /dev/null +++ b/20_timer_callbacks/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff --git a/20_timer_callbacks/kernel/src/symbols.rs b/20_timer_callbacks/kernel/src/symbols.rs new file mode 100644 index 000000000..fdc1d084c --- /dev/null +++ b/20_timer_callbacks/kernel/src/symbols.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Debug symbol support. + +use crate::memory::{Address, Virtual}; +use core::{cell::UnsafeCell, slice}; +use debug_symbol_types::Symbol; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbol from the linker script. +extern "Rust" { + static __kernel_symbols_start: UnsafeCell<()>; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// This will be patched to the correct value by the "kernel symbols tool" after linking. This given +/// value here is just a (safe) dummy. +#[no_mangle] +static NUM_KERNEL_SYMBOLS: u64 = 0; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn kernel_symbol_section_virt_start_addr() -> Address { + Address::new(unsafe { __kernel_symbols_start.get() as usize }) +} + +fn num_kernel_symbols() -> usize { + unsafe { + // Read volatile is needed here to prevent the compiler from optimizing NUM_KERNEL_SYMBOLS + // away. + core::ptr::read_volatile(&NUM_KERNEL_SYMBOLS as *const u64) as usize + } +} + +fn kernel_symbols_slice() -> &'static [Symbol] { + let ptr = kernel_symbol_section_virt_start_addr().as_usize() as *const Symbol; + + unsafe { slice::from_raw_parts(ptr, num_kernel_symbols()) } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Retrieve the symbol corresponding to a virtual address, if any. +pub fn lookup_symbol(addr: Address) -> Option<&'static Symbol> { + kernel_symbols_slice() + .iter() + .find(|&i| i.contains(addr.as_usize())) +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of symbols module. + #[kernel_test] + fn symbols_sanity() { + let first_sym = lookup_symbol(Address::new( + crate::common::is_aligned as *const usize as usize, + )) + .unwrap() + .name(); + + assert_eq!(first_sym, "libkernel::common::is_aligned"); + + let second_sym = lookup_symbol(Address::new(crate::version as *const usize as usize)) + .unwrap() + .name(); + + assert_eq!(second_sym, "libkernel::version"); + } +} diff --git a/20_timer_callbacks/kernel/src/synchronization.rs b/20_timer_callbacks/kernel/src/synchronization.rs new file mode 100644 index 000000000..5740b63e5 --- /dev/null +++ b/20_timer_callbacks/kernel/src/synchronization.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} + +impl InitStateLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use crate::{exception, state}; + +impl interface::Mutex for IRQSafeNullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + + f(data) + } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } +} diff --git a/20_timer_callbacks/kernel/src/time.rs b/20_timer_callbacks/kernel/src/time.rs new file mode 100644 index 000000000..5767a3e63 --- /dev/null +++ b/20_timer_callbacks/kernel/src/time.rs @@ -0,0 +1,263 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. +//! +//! # Resources +//! +//! - +//! - + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use crate::{ + driver, exception, + exception::asynchronous::IRQNumber, + synchronization::{interface::Mutex, IRQSafeNullLock}, + warn, +}; +use alloc::{boxed::Box, vec::Vec}; +use core::{ + sync::atomic::{AtomicBool, Ordering}, + time::Duration, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +struct Timeout { + due_time: Duration, + period: Option, + callback: TimeoutCallback, +} + +struct OrderedTimeoutQueue { + // Can be replaced with a BinaryHeap once it's new() becomes const. + inner: Vec, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The callback type used by timer IRQs. +pub type TimeoutCallback = Box; + +/// Provides time management functions. +pub struct TimeManager { + queue: IRQSafeNullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl Timeout { + pub fn is_periodic(&self) -> bool { + self.period.is_some() + } + + pub fn refresh(&mut self) { + if let Some(delay) = self.period { + self.due_time += delay; + } + } +} + +impl OrderedTimeoutQueue { + pub const fn new() -> Self { + Self { inner: Vec::new() } + } + + pub fn push(&mut self, timeout: Timeout) { + self.inner.push(timeout); + + // Note reverse compare order so that earliest expiring item is at end of vec. We do this so + // that we can use Vec::pop below to retrieve the item that is next due. + self.inner.sort_by(|a, b| b.due_time.cmp(&a.due_time)); + } + + pub fn peek_next_due_time(&self) -> Option { + let timeout = self.inner.last()?; + + Some(timeout.due_time) + } + + pub fn pop(&mut self) -> Option { + self.inner.pop() + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Compatibility string. + pub const COMPATIBLE: &'static str = "ARM Architectural Timer"; + + /// Create an instance. + pub const fn new() -> Self { + Self { + queue: IRQSafeNullLock::new(OrderedTimeoutQueue::new()), + } + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } + + /// Set a timeout. + fn set_timeout(&self, timeout: Timeout) { + self.queue.lock(|queue| { + queue.push(timeout); + + arch_time::set_timeout_irq(queue.peek_next_due_time().unwrap()); + }); + } + + /// Set a one-shot timeout. + pub fn set_timeout_once(&self, delay: Duration, callback: TimeoutCallback) { + let timeout = Timeout { + due_time: self.uptime() + delay, + period: None, + callback, + }; + + self.set_timeout(timeout); + } + + /// Set a periodic timeout. + pub fn set_timeout_periodic(&self, delay: Duration, callback: TimeoutCallback) { + let timeout = Timeout { + due_time: self.uptime() + delay, + period: Some(delay), + callback, + }; + + self.set_timeout(timeout); + } +} + +/// Initialize the timer subsystem. +pub fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + let timer_descriptor = + driver::DeviceDriverDescriptor::new(time_manager(), None, Some(arch_time::timeout_irq())); + driver::driver_manager().register_driver(timer_descriptor); + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for TimeManager { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQHandler for TimeManager { + fn handle(&self) -> Result<(), &'static str> { + arch_time::conclude_timeout_irq(); + + let maybe_timeout: Option = self.queue.lock(|queue| { + let next_due_time = queue.peek_next_due_time()?; + if next_due_time > self.uptime() { + return None; + } + + let mut timeout = queue.pop().unwrap(); + + // Refresh as early as possible to prevent drift. + if timeout.is_periodic() { + timeout.refresh(); + } + + Some(timeout) + }); + + let timeout = match maybe_timeout { + None => { + warn!("Spurious timeout IRQ"); + return Ok(()); + } + Some(t) => t, + }; + + // Important: Call the callback while not holding any lock, because the callback might + // attempt to modify data that is protected by a lock (in particular, the timeout queue + // itself). + (timeout.callback)(); + + self.queue.lock(|queue| { + if timeout.is_periodic() { + // There might be some overhead involved in the periodic path, because the timeout + // item is first popped from the underlying Vec and then pushed back again. It could + // be faster to keep the item in the queue and find a way to work with a reference + // to it. + // + // We are not going this route on purpose, though. It allows to keep the code simple + // and the focus on the high-level concepts. + queue.push(timeout); + }; + + if let Some(due_time) = queue.peek_next_due_time() { + arch_time::set_timeout_irq(due_time); + } + }); + + Ok(()) + } +} diff --git a/20_timer_callbacks/kernel/tests/00_console_sanity.rb b/20_timer_callbacks/kernel/tests/00_console_sanity.rb new file mode 100644 index 000000000..8be7a2f14 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/00_console_sanity.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'console_io_test' + +# Verify sending and receiving works as expected. +class TxRxHandshakeTest < SubtestBase + def name + 'Transmit and Receive handshake' + end + + def run(qemu_out, qemu_in) + qemu_in.write_nonblock('ABC') + expect_or_raise(qemu_out, 'OK1234') + end +end + +# Check for correct TX statistics implementation. Depends on test 1 being run first. +class TxStatisticsTest < SubtestBase + def name + 'Transmit statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '6') + end +end + +# Check for correct RX statistics implementation. Depends on test 1 being run first. +class RxStatisticsTest < SubtestBase + def name + 'Receive statistics' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '3') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] +end diff --git a/20_timer_callbacks/kernel/tests/00_console_sanity.rs b/20_timer_callbacks/kernel/tests/00_console_sanity.rs new file mode 100644 index 000000000..682ea9b8a --- /dev/null +++ b/20_timer_callbacks/kernel/tests/00_console_sanity.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Console sanity tests - RX, TX and statistics. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, console, cpu, exception, memory, print}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + use console::console; + + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Handshake + assert_eq!(console().read_char(), 'A'); + assert_eq!(console().read_char(), 'B'); + assert_eq!(console().read_char(), 'C'); + print!("OK1234"); + + // 6 + print!("{}", console().chars_written()); + + // 3 + print!("{}", console().chars_read()); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/20_timer_callbacks/kernel/tests/01_timer_sanity.rs b/20_timer_callbacks/kernel/tests/01_timer_sanity.rs new file mode 100644 index 000000000..1581a02e0 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/01_timer_sanity.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Timer sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use core::time::Duration; +use libkernel::{bsp, cpu, exception, memory, time}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. + + test_main(); + + cpu::qemu_exit_success() +} + +/// Simple check that the timer is running. +#[kernel_test] +fn timer_is_counting() { + assert!(time::time_manager().uptime().as_nanos() > 0) +} + +/// Timer resolution must be sufficient. +#[kernel_test] +fn timer_resolution_is_sufficient() { + assert!(time::time_manager().resolution().as_nanos() > 0); + assert!(time::time_manager().resolution().as_nanos() < 100) +} + +/// Sanity check spin_for() implementation. +#[kernel_test] +fn spin_accuracy_check_1_second() { + let t1 = time::time_manager().uptime(); + time::time_manager().spin_for(Duration::from_secs(1)); + let t2 = time::time_manager().uptime(); + + assert_eq!((t2 - t1).as_secs(), 1) +} diff --git a/20_timer_callbacks/kernel/tests/02_exception_sync_page_fault.rs b/20_timer_callbacks/kernel/tests/02_exception_sync_page_fault.rs new file mode 100644 index 000000000..09d177981 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/02_exception_sync_page_fault.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Page faults must result in synchronous exceptions. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. +/// +/// In this test, reaching the panic is a success, because it is called from the synchronous +/// exception handler, which is what this test wants to achieve. +/// +/// It also means that this integration test can not use any other code that calls panic!() directly +/// or indirectly. +mod panic_exit_success; + +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing synchronous exception handling by causing a page fault"); + + info!("Writing to bottom of address space to address 1 GiB..."); + let big_addr: u64 = 1024 * 1024 * 1024; + core::ptr::read_volatile(big_addr as *mut u64); + + // If execution reaches here, the memory access above did not cause a page fault exception. + cpu::qemu_exit_failure() +} diff --git a/20_timer_callbacks/kernel/tests/03_exception_restore_sanity.rb b/20_timer_callbacks/kernel/tests/03_exception_restore_sanity.rb new file mode 100644 index 000000000..02f51f741 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/03_exception_restore_sanity.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that exception restore works. +class ExceptionRestoreTest < SubtestBase + def name + 'Exception restore' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Back from system call!') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [ExceptionRestoreTest.new] +end diff --git a/20_timer_callbacks/kernel/tests/03_exception_restore_sanity.rs b/20_timer_callbacks/kernel/tests/03_exception_restore_sanity.rs new file mode 100644 index 000000000..1a3029112 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/03_exception_restore_sanity.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! A simple sanity test to see if exception restore code works. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use core::arch::asm; +use libkernel::{bsp, cpu, exception, info, memory, println}; + +#[inline(never)] +fn nested_system_call() { + #[cfg(target_arch = "aarch64")] + unsafe { + asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); + } + + #[cfg(not(target_arch = "aarch64"))] + { + info!("Not supported yet"); + cpu::wait_forever(); + } +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + // This line will be printed as the test header. + println!("Testing exception restore"); + + info!("Making a dummy system call"); + + // Calling this inside a function indirectly tests if the link register is restored properly. + nested_system_call(); + + info!("Back from system call!"); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever(); +} diff --git a/20_timer_callbacks/kernel/tests/04_exception_irq_sanity.rs b/20_timer_callbacks/kernel/tests/04_exception_irq_sanity.rs new file mode 100644 index 000000000..fcace8979 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception, memory}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + memory::init(); + bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} diff --git a/20_timer_callbacks/kernel/tests/05_backtrace_sanity.rb b/20_timer_callbacks/kernel/tests/05_backtrace_sanity.rb new file mode 100644 index 000000000..243e2fc86 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/05_backtrace_sanity.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Verify that panic produces a backtrace. +class PanicBacktraceTest < SubtestBase + def name + 'Panic produces backtrace' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, 'Kernel panic!') + expect_or_raise(qemu_out, 'Backtrace:') + end +end + +# Verify backtrace correctness. +class BacktraceCorrectnessTest < SubtestBase + def name + 'Backtrace is correct' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, '| core::panicking::panic') + expect_or_raise(qemu_out, '| _05_backtrace_sanity::nested') + expect_or_raise(qemu_out, '| kernel_init') + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [PanicBacktraceTest.new, BacktraceCorrectnessTest.new] +end diff --git a/20_timer_callbacks/kernel/tests/05_backtrace_sanity.rs b/20_timer_callbacks/kernel/tests/05_backtrace_sanity.rs new file mode 100644 index 000000000..66fd0a3e7 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/05_backtrace_sanity.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid frame pointer. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested() { + panic!() +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/20_timer_callbacks/kernel/tests/06_backtrace_invalid_frame.rb b/20_timer_callbacks/kernel/tests/06_backtrace_invalid_frame.rb new file mode 100644 index 000000000..806954682 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/06_backtrace_invalid_frame.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Test detection of invalid frame pointers. +class InvalidFramePointerTest < SubtestBase + def name + 'Detect invalid frame pointer' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, + /Encountered invalid frame pointer \(.*\) during backtrace/) + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [InvalidFramePointerTest.new] +end diff --git a/20_timer_callbacks/kernel/tests/06_backtrace_invalid_frame.rs b/20_timer_callbacks/kernel/tests/06_backtrace_invalid_frame.rs new file mode 100644 index 000000000..38411af69 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/06_backtrace_invalid_frame.rs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid frame pointer. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{backtrace, bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested() { + unsafe { backtrace::corrupt_previous_frame_addr() }; + + panic!() +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/20_timer_callbacks/kernel/tests/07_backtrace_invalid_link.rb b/20_timer_callbacks/kernel/tests/07_backtrace_invalid_link.rb new file mode 100644 index 000000000..6b6f04132 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/07_backtrace_invalid_link.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'console_io_test' + +# Test detection of invalid link. +class InvalidLinkTest < SubtestBase + def name + 'Detect invalid link' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, /Link address \(.*\) is not contained in kernel .text section/) + end +end + +## ------------------------------------------------------------------------------------------------- +## Test registration +## ------------------------------------------------------------------------------------------------- +def subtest_collection + [InvalidLinkTest.new] +end diff --git a/20_timer_callbacks/kernel/tests/07_backtrace_invalid_link.rs b/20_timer_callbacks/kernel/tests/07_backtrace_invalid_link.rs new file mode 100644 index 000000000..6e0873dd1 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/07_backtrace_invalid_link.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Test if backtracing code detects an invalid link. + +#![feature(format_args_nl)] +#![no_main] +#![no_std] + +/// Console tests should time out on the I/O harness in case of panic. +mod panic_wait_forever; + +use libkernel::{backtrace, bsp, cpu, exception, memory}; + +#[inline(never)] +fn nested_2() -> &'static str { + unsafe { backtrace::corrupt_link() }; + libkernel::println!("{}", libkernel::backtrace::Backtrace); + "foo" +} + +#[inline(never)] +fn nested_1() { + libkernel::println!("{}", nested_2()) +} + +#[no_mangle] +unsafe fn kernel_init() -> ! { + exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); + + nested_1(); + + // The QEMU process running this test will be closed by the I/O test harness. + cpu::wait_forever() +} diff --git a/20_timer_callbacks/kernel/tests/boot_test_string.rb b/20_timer_callbacks/kernel/tests/boot_test_string.rb new file mode 100644 index 000000000..d65f1a92e --- /dev/null +++ b/20_timer_callbacks/kernel/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Once 5' diff --git a/20_timer_callbacks/kernel/tests/panic_exit_success/mod.rs b/20_timer_callbacks/kernel/tests/panic_exit_success/mod.rs new file mode 100644 index 000000000..449ad6f9f --- /dev/null +++ b/20_timer_callbacks/kernel/tests/panic_exit_success/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::qemu_exit_success() +} diff --git a/20_timer_callbacks/kernel/tests/panic_wait_forever/mod.rs b/20_timer_callbacks/kernel/tests/panic_wait_forever/mod.rs new file mode 100644 index 000000000..9ac191446 --- /dev/null +++ b/20_timer_callbacks/kernel/tests/panic_wait_forever/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. +#[no_mangle] +fn _panic_exit() -> ! { + libkernel::cpu::wait_forever() +} diff --git a/20_timer_callbacks/kernel_symbols.mk b/20_timer_callbacks/kernel_symbols.mk new file mode 100644 index 000000000..d38b7785a --- /dev/null +++ b/20_timer_callbacks/kernel_symbols.mk @@ -0,0 +1,117 @@ +## SPDX-License-Identifier: MIT OR Apache-2.0 +## +## Copyright (c) 2018-2023 Andre Richter + +include ../common/format.mk +include ../common/docker.mk + +##-------------------------------------------------------------------------------------------------- +## Check for input variables that need be exported by the calling Makefile +##-------------------------------------------------------------------------------------------------- +ifndef KERNEL_SYMBOLS_TOOL_PATH +$(error KERNEL_SYMBOLS_TOOL_PATH is not set) +endif + +ifndef TARGET +$(error TARGET is not set) +endif + +ifndef KERNEL_SYMBOLS_INPUT_ELF +$(error KERNEL_SYMBOLS_INPUT_ELF is not set) +endif + +ifndef KERNEL_SYMBOLS_OUTPUT_ELF +$(error KERNEL_SYMBOLS_OUTPUT_ELF is not set) +endif + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_SYMBOLS_MANIFEST = kernel_symbols/Cargo.toml +KERNEL_SYMBOLS_LINKER_SCRIPT = kernel_symbols/kernel_symbols.ld + +KERNEL_SYMBOLS_RS = $(KERNEL_SYMBOLS_INPUT_ELF)_symbols.rs +KERNEL_SYMBOLS_DEMANGLED_RS = $(shell pwd)/$(KERNEL_SYMBOLS_INPUT_ELF)_symbols_demangled.rs + +KERNEL_SYMBOLS_ELF = target/$(TARGET)/release/kernel_symbols +KERNEL_SYMBOLS_STRIPPED = target/$(TARGET)/release/kernel_symbols_stripped + +# Export for build.rs of kernel_symbols crate. +export KERNEL_SYMBOLS_DEMANGLED_RS + + + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +GET_SYMBOLS_SECTION_VIRT_ADDR = $(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) \ + --get_symbols_section_virt_addr $(KERNEL_SYMBOLS_OUTPUT_ELF) + +RUSTFLAGS = -C link-arg=--script=$(KERNEL_SYMBOLS_LINKER_SCRIPT) \ + -C link-arg=--section-start=.rodata=$$($(GET_SYMBOLS_SECTION_VIRT_ADDR)) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +COMPILER_ARGS = --target=$(TARGET) \ + --release + +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_SYMBOLS_MANIFEST) +OBJCOPY_CMD = rust-objcopy \ + --strip-all \ + -O binary + +EXEC_SYMBOLS_TOOL = ruby $(KERNEL_SYMBOLS_TOOL_PATH)/main.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) + + + +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all symbols measure_time_start measure_time_finish + +all: measure_time_start symbols measure_time_finish + +symbols: + @cp $(KERNEL_SYMBOLS_INPUT_ELF) $(KERNEL_SYMBOLS_OUTPUT_ELF) + + @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --gen_symbols $(KERNEL_SYMBOLS_OUTPUT_ELF) \ + $(KERNEL_SYMBOLS_RS) + + $(call color_progress_prefix, "Demangling") + @echo Symbol names + @cat $(KERNEL_SYMBOLS_RS) | rustfilt > $(KERNEL_SYMBOLS_DEMANGLED_RS) + + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + + $(call color_progress_prefix, "Stripping") + @echo Symbols ELF file + @$(OBJCOPY_CMD) $(KERNEL_SYMBOLS_ELF) $(KERNEL_SYMBOLS_STRIPPED) + + @$(DOCKER_TOOLS) $(EXEC_SYMBOLS_TOOL) --patch_data $(KERNEL_SYMBOLS_OUTPUT_ELF) \ + $(KERNEL_SYMBOLS_STRIPPED) + +# Note: The following is the only _trivial_ way I could think of that works out of the box on both +# Linux and macOS. Since macOS does not have the %N nanosecond format string option, the +# resolution is restricted to whole seconds. +measure_time_start: + @date +%s > /tmp/kernel_symbols_start.date + +measure_time_finish: + @date +%s > /tmp/kernel_symbols_end.date + + $(call color_progress_prefix, "Finished") + @echo "in $$((`cat /tmp/kernel_symbols_end.date` - `cat /tmp/kernel_symbols_start.date`)).0s" + + @rm /tmp/kernel_symbols_end.date /tmp/kernel_symbols_start.date diff --git a/20_timer_callbacks/kernel_symbols/Cargo.lock b/20_timer_callbacks/kernel_symbols/Cargo.lock new file mode 100644 index 000000000..70b7fa662 --- /dev/null +++ b/20_timer_callbacks/kernel_symbols/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "debug-symbol-types" +version = "0.1.0" + +[[package]] +name = "kernel_symbols" +version = "0.1.0" +dependencies = [ + "debug-symbol-types", +] diff --git a/20_timer_callbacks/kernel_symbols/Cargo.toml b/20_timer_callbacks/kernel_symbols/Cargo.toml new file mode 100644 index 000000000..3407aa7e1 --- /dev/null +++ b/20_timer_callbacks/kernel_symbols/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "kernel_symbols" +version = "0.1.0" +edition = "2021" + +[features] +default = [] +generated_symbols_available = [] + +##-------------------------------------------------------------------------------------------------- +## Dependencies +##-------------------------------------------------------------------------------------------------- + +[dependencies] +debug-symbol-types = { path = "../libraries/debug-symbol-types" } diff --git a/20_timer_callbacks/kernel_symbols/build.rs b/20_timer_callbacks/kernel_symbols/build.rs new file mode 100644 index 000000000..5062df444 --- /dev/null +++ b/20_timer_callbacks/kernel_symbols/build.rs @@ -0,0 +1,14 @@ +use std::{env, path::Path}; + +fn main() { + if let Ok(path) = env::var("KERNEL_SYMBOLS_DEMANGLED_RS") { + if Path::new(&path).exists() { + println!("cargo:rustc-cfg=feature=\"generated_symbols_available\"") + } + } + + println!( + "cargo:rerun-if-changed={}", + Path::new("kernel_symbols.ld").display() + ); +} diff --git a/20_timer_callbacks/kernel_symbols/kernel_symbols.ld b/20_timer_callbacks/kernel_symbols/kernel_symbols.ld new file mode 100644 index 000000000..16724a07d --- /dev/null +++ b/20_timer_callbacks/kernel_symbols/kernel_symbols.ld @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2022-2023 Andre Richter + */ + +SECTIONS +{ + .rodata : { + ASSERT(. > 0xffffffff00000000, "Expected higher half address") + + KEEP(*(.rodata.symbol_desc*)) + . = ALIGN(8); + *(.rodata*) + } +} diff --git a/20_timer_callbacks/kernel_symbols/src/main.rs b/20_timer_callbacks/kernel_symbols/src/main.rs new file mode 100644 index 000000000..38ce18f8f --- /dev/null +++ b/20_timer_callbacks/kernel_symbols/src/main.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Generation of kernel symbols. + +#![no_std] +#![no_main] + +#[cfg(feature = "generated_symbols_available")] +include!(env!("KERNEL_SYMBOLS_DEMANGLED_RS")); + +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + unimplemented!() +} diff --git a/20_timer_callbacks/libraries/debug-symbol-types/Cargo.toml b/20_timer_callbacks/libraries/debug-symbol-types/Cargo.toml new file mode 100644 index 000000000..e5b1fd1f5 --- /dev/null +++ b/20_timer_callbacks/libraries/debug-symbol-types/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "debug-symbol-types" +version = "0.1.0" +edition = "2021" diff --git a/20_timer_callbacks/libraries/debug-symbol-types/src/lib.rs b/20_timer_callbacks/libraries/debug-symbol-types/src/lib.rs new file mode 100644 index 000000000..81c897bfa --- /dev/null +++ b/20_timer_callbacks/libraries/debug-symbol-types/src/lib.rs @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Types for implementing debug symbol support. + +#![no_std] + +use core::ops::Range; + +/// A symbol containing a size. +#[repr(C)] +#[derive(Clone)] +pub struct Symbol { + addr_range: Range, + name: &'static str, +} + +impl Symbol { + /// Create an instance. + pub const fn new(start: usize, size: usize, name: &'static str) -> Symbol { + Symbol { + addr_range: Range { + start, + end: start + size, + }, + name, + } + } + + /// Returns true if addr is contained in the range. + pub fn contains(&self, addr: usize) -> bool { + self.addr_range.contains(&addr) + } + + /// Returns the symbol's name. + pub fn name(&self) -> &'static str { + self.name + } + + /// Returns the symbol's size. + pub fn size(&self) -> usize { + self.addr_range.end - self.addr_range.start + } +} diff --git a/20_timer_callbacks/libraries/test-macros/Cargo.toml b/20_timer_callbacks/libraries/test-macros/Cargo.toml new file mode 100644 index 000000000..fff98a1fc --- /dev/null +++ b/20_timer_callbacks/libraries/test-macros/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "test-macros" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.x" +quote = "1.x" +syn = { version = "1.x", features = ["full"] } +test-types = { path = "../test-types" } diff --git a/20_timer_callbacks/libraries/test-macros/src/lib.rs b/20_timer_callbacks/libraries/test-macros/src/lib.rs new file mode 100644 index 000000000..52cf893dd --- /dev/null +++ b/20_timer_callbacks/libraries/test-macros/src/lib.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +use proc_macro::TokenStream; +use proc_macro2::Span; +use quote::quote; +use syn::{parse_macro_input, Ident, ItemFn}; + +#[proc_macro_attribute] +pub fn kernel_test(_attr: TokenStream, input: TokenStream) -> TokenStream { + let f = parse_macro_input!(input as ItemFn); + + let test_name = &format!("{}", f.sig.ident); + let test_ident = Ident::new( + &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), + Span::call_site(), + ); + let test_code_block = f.block; + + quote!( + #[test_case] + const #test_ident: test_types::UnitTest = test_types::UnitTest { + name: #test_name, + test_func: || #test_code_block, + }; + ) + .into() +} diff --git a/20_timer_callbacks/libraries/test-types/Cargo.toml b/20_timer_callbacks/libraries/test-types/Cargo.toml new file mode 100644 index 000000000..2f20f060e --- /dev/null +++ b/20_timer_callbacks/libraries/test-types/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "test-types" +version = "0.1.0" +authors = ["Andre Richter "] +edition = "2021" diff --git a/20_timer_callbacks/libraries/test-types/src/lib.rs b/20_timer_callbacks/libraries/test-types/src/lib.rs new file mode 100644 index 000000000..38961a9ce --- /dev/null +++ b/20_timer_callbacks/libraries/test-types/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2019-2023 Andre Richter + +//! Types for the `custom_test_frameworks` implementation. + +#![no_std] + +/// Unit test container. +pub struct UnitTest { + /// Name of the test. + pub name: &'static str, + + /// Function pointer to the test. + pub test_func: fn(), +} diff --git a/20_timer_callbacks/tools/kernel_symbols_tool/cmds.rb b/20_timer_callbacks/tools/kernel_symbols_tool/cmds.rb new file mode 100644 index 000000000..c43acb24c --- /dev/null +++ b/20_timer_callbacks/tools/kernel_symbols_tool/cmds.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +def generate_symbols(kernel_elf, output_file) + File.open(output_file, 'w') do |file| + header = <<~HEREDOC + use debug_symbol_types::Symbol; + + # [no_mangle] + # [link_section = ".rodata.symbol_desc"] + static KERNEL_SYMBOLS: [Symbol; #{kernel_elf.num_symbols}] = [ + HEREDOC + + file.write(header) + kernel_elf.symbols.each do |sym| + value = sym.header.st_value + size = sym.header.st_size + name = sym.name + + file.write(" Symbol::new(#{value}, #{size}, \"#{name}\"),\n") + end + file.write("];\n") + end +end + +def get_symbols_section_virt_addr(kernel_elf) + kernel_elf.kernel_symbols_section_virt_addr +end + +def patch_symbol_data(kernel_elf, symbols_blob_path) + symbols_blob = File.binread(symbols_blob_path) + + raise if symbols_blob.size > kernel_elf.kernel_symbols_section_size + + File.binwrite(kernel_elf.path, File.binread(symbols_blob_path), + kernel_elf.kernel_symbols_section_offset_in_file) +end + +def patch_num_symbols(kernel_elf) + num_packed = [kernel_elf.num_symbols].pack('Q<*') # "Q" == uint64_t, "<" == little endian + File.binwrite(kernel_elf.path, num_packed, kernel_elf.num_kernel_symbols_offset_in_file) +end diff --git a/20_timer_callbacks/tools/kernel_symbols_tool/kernel_elf.rb b/20_timer_callbacks/tools/kernel_symbols_tool/kernel_elf.rb new file mode 100644 index 000000000..32b5460aa --- /dev/null +++ b/20_timer_callbacks/tools/kernel_symbols_tool/kernel_elf.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + attr_reader :path + + def initialize(kernel_elf_path, kernel_symbols_section, num_kernel_symbols) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + + @path = kernel_elf_path + fetch_values(kernel_symbols_section, num_kernel_symbols) + end + + private + + def fetch_values(kernel_symbols_section, num_kernel_symbols) + sym = @symtab_section.symbol_by_name(num_kernel_symbols) + raise "Symbol \"#{num_kernel_symbols}\" not found" if sym.nil? + + @num_kernel_symbols = sym + + section = @elf.section_by_name(kernel_symbols_section) + raise "Section \"#{kernel_symbols_section}\" not found" if section.nil? + + @kernel_symbols_section = section + end + + def num_kernel_symbols_virt_addr + @num_kernel_symbols.header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + public + + def symbols + non_zero_symbols = @symtab_section.symbols.reject { |sym| sym.header.st_size.zero? } + non_zero_symbols.sort_by { |sym| sym.header.st_value } + end + + def num_symbols + symbols.size + end + + def kernel_symbols_section_virt_addr + @kernel_symbols_section.header.sh_addr.to_i + end + + def kernel_symbols_section_size + @kernel_symbols_section.header.sh_size.to_i + end + + def kernel_symbols_section_offset_in_file + virt_addr_to_file_offset(kernel_symbols_section_virt_addr) + end + + def num_kernel_symbols_offset_in_file + virt_addr_to_file_offset(num_kernel_symbols_virt_addr) + end +end diff --git a/20_timer_callbacks/tools/kernel_symbols_tool/main.rb b/20_timer_callbacks/tools/kernel_symbols_tool/main.rb new file mode 100755 index 000000000..899f96464 --- /dev/null +++ b/20_timer_callbacks/tools/kernel_symbols_tool/main.rb @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2022-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'kernel_elf' +require_relative 'cmds' + +KERNEL_SYMBOLS_SECTION = '.kernel_symbols' +NUM_KERNEL_SYMBOLS = 'NUM_KERNEL_SYMBOLS' + +cmd = ARGV[0] + +kernel_elf_path = ARGV[1] +kernel_elf = KernelELF.new(kernel_elf_path, KERNEL_SYMBOLS_SECTION, NUM_KERNEL_SYMBOLS) + +case cmd +when '--gen_symbols' + output_file = ARGV[2] + + print 'Generating'.rjust(12).green.bold + puts ' Symbols source file' + + generate_symbols(kernel_elf, output_file) +when '--get_symbols_section_virt_addr' + addr = get_symbols_section_virt_addr(kernel_elf) + + puts "0x#{addr.to_s(16)}" +when '--patch_data' + symbols_blob_path = ARGV[2] + num_symbols = kernel_elf.num_symbols + + print 'Patching'.rjust(12).green.bold + puts " Symbols blob and number of symbols (#{num_symbols}) into ELF" + + patch_symbol_data(kernel_elf, symbols_blob_path) + patch_num_symbols(kernel_elf) +else + raise +end diff --git a/20_timer_callbacks/tools/translation_table_tool/arch.rb b/20_timer_callbacks/tools/translation_table_tool/arch.rb new file mode 100644 index 000000000..053cac194 --- /dev/null +++ b/20_timer_callbacks/tools/translation_table_tool/arch.rb @@ -0,0 +1,314 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Bitfield manipulation. +class BitField + def initialize + @value = 0 + end + + def self.attr_bitfield(name, offset, num_bits) + define_method("#{name}=") do |bits| + mask = (2**num_bits) - 1 + + raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? + + # Clear bitfield + @value &= ~(mask << offset) + + # Set it + @value |= (bits << offset) + end + end + + def to_i + @value + end + + def size_in_byte + 8 + end +end + +# An array class that knows its memory location. +class CArray < Array + attr_reader :phys_start_addr + + def initialize(phys_start_addr, size, &block) + @phys_start_addr = phys_start_addr + + super(size, &block) + end + + def size_in_byte + inject(0) { |sum, n| sum + n.size_in_byte } + end +end + +#--------------------------------------------------------------------------------------------------- +# Arch:: +#--------------------------------------------------------------------------------------------------- +module Arch +#--------------------------------------------------------------------------------------------------- +# Arch::ARMv8 +#--------------------------------------------------------------------------------------------------- +module ARMv8 +# ARMv8 Table Descriptor. +class Stage1TableDescriptor < BitField + module NextLevelTableAddr + OFFSET = 16 + NUMBITS = 32 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + BLOCK = 0 + TABLE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def next_level_table_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__next_level_table_addr = addr + end + + private :__next_level_table_addr= +end + +# ARMv8 level 3 page descriptor. +class Stage1PageDescriptor < BitField + module UXN + OFFSET = 54 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module PXN + OFFSET = 53 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module OutputAddr + OFFSET = 16 + NUMBITS = 32 + end + + module AF + OFFSET = 10 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module SH + OFFSET = 8 + NUMBITS = 2 + + INNER_SHAREABLE = 0b11 + end + + module AP + OFFSET = 6 + NUMBITS = 2 + + RW_EL1 = 0b00 + RO_EL1 = 0b10 + end + + module AttrIndx + OFFSET = 2 + NUMBITS = 3 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + RESERVED_INVALID = 0 + PAGE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) + attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) + attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) + attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) + attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) + attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) + attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def output_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__output_addr = addr + end + + private :__output_addr= +end + +# Translation table representing the structure defined in translation_table.rs. +class TranslationTable + module MAIR + NORMAL = 1 + end + + def initialize + do_sanity_checks + + num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT + + @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) + + @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte + @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) + + populate_lvl2_entries + end + + def map_at(virt_region, phys_region, attributes) + return if virt_region.empty? + + raise if virt_region.size != phys_region.size + raise if phys_region.last > BSP.phys_addr_space_end_page + + virt_region.zip(phys_region).each do |virt_page, phys_page| + desc = page_descriptor_from(virt_page) + set_lvl3_entry(desc, phys_page, attributes) + end + end + + def to_binary + data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) + data.pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr_binary + [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr + @lvl2_phys_start_addr + end + + private + + def do_sanity_checks + raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE + raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? + end + + def new_lvl3(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + temp = CArray.new(start_addr, 8192) do + Stage1PageDescriptor.new + end + start_addr += temp.size_in_byte + + temp + end + end + + def new_lvl2(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + Stage1TableDescriptor.new + end + end + + def populate_lvl2_entries + @lvl2.each_with_index do |descriptor, i| + descriptor.next_level_table_addr = @lvl3[i].phys_start_addr + descriptor.type = Stage1TableDescriptor::Type::TABLE + descriptor.valid = Stage1TableDescriptor::Valid::TRUE + end + end + + def lvl2_lvl3_index_from(addr) + addr -= BSP.kernel_virt_start_addr + + lvl2_index = addr >> Granule512MiB::SHIFT + lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT + + raise unless lvl2_index < @lvl2.size + + [lvl2_index, lvl3_index] + end + + def page_descriptor_from(virt_addr) + lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) + + @lvl3[lvl2_index][lvl3_index] + end + + # rubocop:disable Metrics/MethodLength + def set_attributes(desc, attributes) + case attributes.mem_attributes + when :CacheableDRAM + desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE + desc.attr_indx = MAIR::NORMAL + else + raise 'Invalid input' + end + + desc.ap = case attributes.acc_perms + when :ReadOnly + Stage1PageDescriptor::AP::RO_EL1 + when :ReadWrite + Stage1PageDescriptor::AP::RW_EL1 + else + raise 'Invalid input' + + end + + desc.pxn = if attributes.execute_never + Stage1PageDescriptor::PXN::TRUE + else + Stage1PageDescriptor::PXN::FALSE + end + + desc.uxn = Stage1PageDescriptor::UXN::TRUE + end + # rubocop:enable Metrics/MethodLength + + def set_lvl3_entry(desc, output_addr, attributes) + desc.output_addr = output_addr + desc.af = Stage1PageDescriptor::AF::TRUE + desc.type = Stage1PageDescriptor::Type::PAGE + desc.valid = Stage1PageDescriptor::Valid::TRUE + + set_attributes(desc, attributes) + end +end +end +end diff --git a/20_timer_callbacks/tools/translation_table_tool/bsp.rb b/20_timer_callbacks/tools/translation_table_tool/bsp.rb new file mode 100644 index 000000000..5887d7745 --- /dev/null +++ b/20_timer_callbacks/tools/translation_table_tool/bsp.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Raspberry Pi 3 + 4 +class RaspberryPi + attr_reader :kernel_granule, :kernel_virt_addr_space_size, :kernel_virt_start_addr + + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + + def initialize + @kernel_granule = Granule64KiB + + @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') + @kernel_virt_start_addr = KERNEL_ELF.symbol_value('__kernel_virt_start_addr') + + @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') + @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( + 'PHYS_KERNEL_TABLES_BASE_ADDR' + ) + end + + def phys_addr_of_kernel_tables + KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) + end + + def kernel_tables_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) + end + + def phys_kernel_tables_base_addr_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) + end + + def phys_addr_space_end_page + x = MEMORY_SRC.grep(/pub const END/) + x = case BSP_TYPE + when :rpi3 + x[0] + when :rpi4 + x[1] + else + raise + end + + # Extract the hex literal with underscores like 0x0123_abcd. + x = x.scan(/0x[\h_]*/)[0] + + # Further remove x and _ and convert to int. + x.scan(/\h+/).join.to_i(16) + end +end diff --git a/20_timer_callbacks/tools/translation_table_tool/generic.rb b/20_timer_callbacks/tools/translation_table_tool/generic.rb new file mode 100644 index 000000000..941e2226f --- /dev/null +++ b/20_timer_callbacks/tools/translation_table_tool/generic.rb @@ -0,0 +1,189 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +module Granule64KiB + SIZE = 64 * 1024 + SHIFT = Math.log2(SIZE).to_i +end + +module Granule512MiB + SIZE = 512 * 1024 * 1024 + SHIFT = Math.log2(SIZE).to_i + MASK = SIZE - 1 +end + +# Monkey-patch Integer with some helper functions. +class Integer + def power_of_two? + self[0].zero? + end + + def aligned?(alignment) + raise unless alignment.power_of_two? + + (self & (alignment - 1)).zero? + end + + def align_up(alignment) + raise unless alignment.power_of_two? + + (self + alignment - 1) & ~(alignment - 1) + end + + def to_hex_underscore(with_leading_zeros: false) + fmt = with_leading_zeros ? '%016x' : '%x' + value = format(fmt, self).to_s.reverse.scan(/.{4}|.+/).join('_').reverse + + format('0x%s', value) + end +end + +# An array where each value is the start address of a Page. +class MemoryRegion < Array + def initialize(start_addr, size, granule_size) + raise unless start_addr.aligned?(granule_size) + raise unless size.positive? + raise unless (size % granule_size).zero? + + num_pages = size / granule_size + super(num_pages) do |i| + (i * granule_size) + start_addr + end + end +end + +# Collection of memory attributes. +class AttributeFields + attr_reader :mem_attributes, :acc_perms, :execute_never + + def initialize(mem_attributes, acc_perms, execute_never) + @mem_attributes = mem_attributes + @acc_perms = acc_perms + @execute_never = execute_never + end + + def to_s + x = case @mem_attributes + when :CacheableDRAM + 'C' + else + '?' + end + + y = case @acc_perms + when :ReadWrite + 'RW' + when :ReadOnly + 'RO' + else + '??' + end + + z = @execute_never ? 'XN' : 'X ' + + "#{x} #{y} #{z}" + end +end + +# A container that describes a virt-to-phys region mapping. +class MappingDescriptor + @max_section_name_length = 'Sections'.length + + class << self + attr_accessor :max_section_name_length + + def update_max_section_name_length(length) + @max_section_name_length = [@max_section_name_length, length].max + end + end + + attr_reader :name, :virt_region, :phys_region, :attributes + + def initialize(name, virt_region, phys_region, attributes) + @name = name + @virt_region = virt_region + @phys_region = phys_region + @attributes = attributes + end + + def size_human_readable(size) + if size >= (1024 * 1024) + "#{(size / (1024 * 1024)).to_s.rjust(3)} MiB" + elsif size >= 1024 + "#{(size / 1024).to_s.rjust(3)} KiB" + else + raise + end + end + + def to_s + name = @name.ljust(self.class.max_section_name_length) + virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) + phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) + size = size_human_readable(@virt_region.size * 65_536) + + "#{name} | #{virt_start} | #{phys_start} | #{size} | #{@attributes}" + end + + def self.print_divider + print ' ' + print '-' * max_section_name_length + puts '--------------------------------------------------------------------' + end + + def self.print_header + print_divider + print ' ' + print 'Sections'.center(max_section_name_length) + print ' ' + print 'Virt Start Addr'.center(21) + print ' ' + print 'Phys Start Addr'.center(21) + print ' ' + print 'Size'.center(7) + print ' ' + print 'Attr'.center(7) + puts + print_divider + end +end + +def kernel_map_binary + mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors + + # Generate_mapping_descriptors updates the header being printed with this call. So it must come + # afterwards. + MappingDescriptor.print_header + + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' + puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end + + MappingDescriptor.print_divider +end + +def kernel_patch_tables(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel table struct at ELF file offset ' + puts BSP.kernel_tables_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.to_binary, BSP.kernel_tables_offset_in_file) +end + +def kernel_patch_base_addr(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel tables physical base address start argument to value ' + print TRANSLATION_TABLES.phys_tables_base_addr.to_hex_underscore + print ' at ELF file offset ' + puts BSP.phys_kernel_tables_base_addr_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.phys_tables_base_addr_binary, + BSP.phys_kernel_tables_base_addr_offset_in_file) +end diff --git a/20_timer_callbacks/tools/translation_table_tool/kernel_elf.rb b/20_timer_callbacks/tools/translation_table_tool/kernel_elf.rb new file mode 100644 index 000000000..5ba78d9df --- /dev/null +++ b/20_timer_callbacks/tools/translation_table_tool/kernel_elf.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + SECTION_FLAG_ALLOC = 2 + + def initialize(kernel_elf_path) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + end + + def machine + @elf.machine.to_sym + end + + def symbol_value(symbol_name) + @symtab_section.symbol_by_name(symbol_name).header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_to_phys(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + translation_offset = segment.header.p_vaddr - segment.header.p_paddr + + virt_addr - translation_offset + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + def sections_in_segment(segment) + head = segment.mem_head + tail = segment.mem_tail + + sections = @elf.each_sections.select do |section| + file_offset = section.header.sh_addr + flags = section.header.sh_flags + + file_offset >= head && file_offset < tail && (flags & SECTION_FLAG_ALLOC != 0) + end + + sections.map(&:name).join(' ') + end + + def select_load_segments + @elf.each_segments.select do |segment| + segment.instance_of?(ELFTools::Segments::LoadSegment) + end + end + + def segment_get_acc_perms(segment) + if segment.readable? && segment.writable? + :ReadWrite + elsif segment.readable? + :ReadOnly + else + :Invalid + end + end + + def update_max_section_name_length(descriptors) + MappingDescriptor.update_max_section_name_length(descriptors.map { |i| i.name.size }.max) + end + + def generate_mapping_descriptors + descriptors = select_load_segments.map do |segment| + # Assume each segment is page aligned. + size = segment.mem_size.align_up(BSP.kernel_granule::SIZE) + virt_start_addr = segment.header.p_vaddr + phys_start_addr = segment.header.p_paddr + acc_perms = segment_get_acc_perms(segment) + execute_never = !segment.executable? + section_names = sections_in_segment(segment) + + virt_region = MemoryRegion.new(virt_start_addr, size, BSP.kernel_granule::SIZE) + phys_region = MemoryRegion.new(phys_start_addr, size, BSP.kernel_granule::SIZE) + attributes = AttributeFields.new(:CacheableDRAM, acc_perms, execute_never) + + MappingDescriptor.new(section_names, virt_region, phys_region, attributes) + end + + update_max_section_name_length(descriptors) + descriptors + end +end diff --git a/20_timer_callbacks/tools/translation_table_tool/main.rb b/20_timer_callbacks/tools/translation_table_tool/main.rb new file mode 100755 index 000000000..22ab24fd5 --- /dev/null +++ b/20_timer_callbacks/tools/translation_table_tool/main.rb @@ -0,0 +1,46 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'generic' +require_relative 'kernel_elf' +require_relative 'bsp' +require_relative 'arch' + +BSP_TYPE = ARGV[0].to_sym +kernel_elf_path = ARGV[1] + +start = Time.now + +KERNEL_ELF = KernelELF.new(kernel_elf_path) + +BSP = case BSP_TYPE + when :rpi3, :rpi4 + RaspberryPi.new + else + raise + end + +TRANSLATION_TABLES = case KERNEL_ELF.machine + when :AArch64 + Arch::ARMv8::TranslationTable.new + else + raise + end + +kernel_map_binary +kernel_patch_tables(kernel_elf_path) +kernel_patch_base_addr(kernel_elf_path) + +elapsed = Time.now - start + +print 'Finished'.rjust(12).green.bold +puts " in #{elapsed.round(2)}s" diff --git a/Gemfile b/Gemfile index b6fad4ea1..7460e0481 100644 --- a/Gemfile +++ b/Gemfile @@ -3,6 +3,7 @@ source 'https://rubygems.org' gem 'colorize' +gem 'elftools' group :uart do gem 'ruby-progressbar' @@ -10,5 +11,5 @@ group :uart do end group :development do - gem 'rubocop', '>= 1.4.1', require: false + gem 'rubocop', '>= 1.38.0', require: false end diff --git a/LICENSE-MIT b/LICENSE-MIT index e91db966e..af7f918ff 100644 --- a/LICENSE-MIT +++ b/LICENSE-MIT @@ -1,6 +1,6 @@ MIT License -Copyright (C) 2018-2020 by the respective authors +Copyright (C) 2018-2023 by the respective authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.CN.md b/README.CN.md index ed767da69..1b44067b6 100644 --- a/README.CN.md +++ b/README.CN.md @@ -48,34 +48,32 @@ _带上我最诚挚的问候,
Andre ([@andre-richter])_ ### 🚀 tl;dr 版本 1. [安装 Docker][install_docker]。 -2. 确保你的用户在 [docker group] 中。 -3. 安装正确的`Rust`工具链: +2. **(仅限Linux)** 确保您的用户帐户在 [docker group] 中。 +3. 准备Rust工具链。其中大部分将在首次使用时通过[rust-toolchain.toml](rust-toolchain.toml)文件进行处理。我们要做的是: 1. 如果你已经安装了一个版本的Rust: ```bash - rustup toolchain add nightly-2020-11-20 - rustup default nightly-2020-11-20 - rustup component add llvm-tools-preview - rustup target add aarch64-unknown-none-softfloat cargo install cargo-binutils rustfilt ``` - 2. 如果你想要全新安装: + 1. 如果你想要全新安装: ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- \ - --default-toolchain nightly-2020-11-20 \ - --component llvm-tools-preview + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env - rustup target add aarch64-unknown-none-softfloat cargo install cargo-binutils rustfilt ``` 4. 如果你使用 `Visual Studio Code`,我强烈推荐你安装[Rust Analyzer 扩展]。 -5. 如果你使用的**不是**Linux,那么你还需要安装一些`Ruby` gems。 +5. **(仅限macOS)** 安装一些`Ruby` gems。 + +这是作者最后一次在`macOS Monterey`上用`Ruby 3.0.2`版本进行测试。如果您正在使用`rbenv`,那么相应的`.ruby-version`文件已经就位。 +如果你从未听说过`rbenv`,请尝试使用[这个指南](https://stackoverflow.com/a/68118750)。 + +在存储库根文件夹中运行此操作: ```bash -sudo gem install bundler -bundle config set path '.vendor/bundle' +bundle config set --local path '.vendor/bundle' +bundle config set --local without 'development' bundle install ``` @@ -85,9 +83,10 @@ bundle install ## 🧰 长期版本: 消除工具链烦恼 -这个系列的教程会着重关注用户体验的友好性。因此,我尽量消除嵌入式开发中的最大痛点:工具链的问题。 +这个系列的教程会着重关注用户体验的友好性。因此,我尽量消除嵌入式开发中的最大痛点:`Toolchain hassle`。 Rust内置的交叉编译支持在这方面帮了我们大忙。我们只需要使用`rustup`安装目标工具链就可以在`x86`宿主机上交叉编译支持树莓派的目标文件。然而,除了Rust编译器,我们还需要更多的工具。例如: +Rust本身在这方面已经起到了很大的作用,因为它内置了对交叉编译的支持。从`x86`宿主机到树莓派的`AArch64`架构的交叉编译所需的一切都将由`rustup`自动安装。然而,除了Rust编译器,我们还将使用更多的工具。例如: - 用于在我们的宿主系统上模拟我们内核运行环境的`QEMU`。 - 一个叫`Minipush`的自制工具,可以通过`UART`将内核加载到树莓派上。 @@ -101,17 +100,20 @@ Rust内置的交叉编译支持在这方面帮了我们大忙。我们只需要 ## 📟 USB 串行输出 -由于教程中开发的内核是在真实的硬件上运行的,因此强烈建议您使用 USB 串行调试线来进行试验。连接后调试线会为树莓派供电, -所以不需要额外供电。 +由于教程中开发的内核是在真实的硬件上运行的,因此强烈建议您使用 USB 串行调试线来进行试验。连接调试线后,树莓派需要通过额外电源供电。 -- 淘宝搜索"USB 转串口" -- 如下图连接 GPIO 串口的 14/15 号引脚 -- [第六章](06_drivers_gpio_uart) 是这个设备第一次需要使用的地方。找到如何准备 SD 卡来引导你自制的内核的说明。 -- [第七章](07_uart_chainloader)开始,在树莓派上启动内核变得非常舒适。在这章,会开发出一个叫`chainloader`的文件。 - 这将是您暂时需要在 SD 卡上手动复制的最后一个文件。这将使您能够在通过 UART 按需引导期间加载教程内核。 +- 您可以在[\[1\]] [\[2\]]中或者[淘宝]上找到USB转串口线,但许多其他线材也可以工作。理想情况下,您的线材应基于`CP2102`芯片。 +- 您将其连接到`GND`和GPIO引脚`14/15`,如下所示。 +- [教程5](05_drivers_gpio_uart/README.CN.md)是这个设备第一次需要使用的地方。查看它了解如何准备SD卡以从中启动自制内核的说明。 +- 从[教程6](06_uart_chainloader/README.CN.md)开始,在树莓派上启动内核变得非常舒适。在本教程中开发了一个所谓的`chainloader`,。 + 这将是您暂时需要在SD卡上手动复制的最后一个文件。这将使您能够在通过`UART`按需引导期间加载教程内核。 ![UART wiring diagram](doc/wiring.png) +[\[1\]]: https://www.amazon.de/dp/B0757FQ5CX/ref=cm_sw_r_tw_dp_U_x_ozGRDbVTJAG4Q +[\[2\]]: https://www.adafruit.com/product/954 +[淘宝]: https://www.taobao.com/ + ## 🙌 致谢 这个教程最初是由[Zoltan Baldaszti](https://github.com/bztsrc)的[项目](https://github.com/bztsrc/raspi3-tutorial)衍生出来的,感谢它给我开了一个头。 diff --git a/README.ES.md b/README.ES.md new file mode 100644 index 000000000..16619dd0c --- /dev/null +++ b/README.ES.md @@ -0,0 +1,173 @@ +# Tutoriales de desarrollo de Sistemas Operativos en Rust con la Raspberry Pi + +![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/BSP-RPi3/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/BSP-RPi4/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/Unit-Tests/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/Integration-Tests/badge.svg) ![](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue) + +
+ + + +## ℹ️ Introducción + +Esto es una serie de tutoriales para los desarrolladores aficionados a los Sistemas Operativos (OS) +que se están adentrando a la nueva arquitectura ARM de 64 bits [ARMv8-A +architecture]. Los tutoriales darán una guía paso a paso en cómo escribir un Sistema Operativo +[monolítico] desde cero. +Estos tutoriales cubren la implementación común de diferentes tareas de Sistemas Operativos, como +escribir en una terminal serie, configurar la memoria virtual y manejar excepciones de hardware (HW). +Todo mientras usamos la seguridad y velocidad que `Rust` nos proporciona. + +¡Divértanse! + +_Atentamente,
Andre ([@andre-richter])_ + +P.S.: Para otros lenguajes, por favor busquen los diferentes archivos README. Por ejemplo, [`README.CN.md`](README.CN.md) o [`README.ES.md`](README.ES.md). Muchas gracias a nuestros +[traductores](#traducciones-de-este-repositorio) 🙌. + +[ARMv8-A architecture]: https://developer.arm.com/products/architecture/cpu-architecture/a-profile/docs +[monolítico]: https://en.wikipedia.org/wiki/Monolithic_kernel +[@andre-richter]: https://github.com/andre-richter + +## 📑 Estructura + +- Cada tutorial contiene un solo binario arrancable correspondiente al núcleo. +- Cada tutorial nuevo extiende el tutorial anterior. +- Cada tutorial tendrá un `README` y cada `README` tendrá un pequeña sección de [`tl;dr`](https://es.wikipedia.org/wiki/TL;DR) en donde se dará una pequeña perspectiva general de los cambios y se mostrará el código fuente `diff` del tutorial anterior para que se puedan inspeccionar los cambios/adiciones que han ocurrido. + - Algunos tutoriales además de tener un `tl;dr` también tendrán una sección en la que se dará una explicación con todo lujo de detalle. + El plan a largo plazo es que cada tutorial tenga una buena explicación además del `tl;dr` y el `diff`; pero por el momento los únicos tutoriales + que gozan de una son los tutoriales en los que creo que el `tl;dr` y el `diff` no son suficientes para comprender lo que está pasando. +- El código que se escribió en este tutorial soporta y corre en la **Raspberry Pi 3** y en la **Raspberry 4** + - Del tutorial 1 hasta el 5 son tutoriales "preparatorios", por lo que este código solo tendrá sentido ejecutarlo en [`QEMU`](https://www.qemu.org/). + - Cuando llegues al [tutorial 5](05_drivers_gpio_uart) podrás comenzar a cargar y a ejecutar el núcleo en una + Raspeberry de verdad, y observar la salida serie (`UART`). +- Aunque la Raspberry Pi 3 y 4 son las principales placas este código está escrito en un estilo modular, + lo que permite una fácil portabilidad a otras arquitecturas de CPU o/y placas. + - Me encantaría si alguien intentase adaptar este código en una arquitectura **RISC-V**. +- Para la edición recomiendo [Visual Studio Code] con [Rust Analyzer]. +- En adición al texto que aparece en los tutoriales también sería recomendable revisar + el comando `make doc` en cada tutorial. Este comando te deja navegar el código documentado de una manera cómoda. + +### Salida del comando `make doc` + +![make doc](doc/make_doc.png) + +[Visual Studio Code]: https://code.visualstudio.com +[Rust Analyzer]: https://rust-analyzer.github.io + +## 🛠 Requisitos del sistema + +Estos tutoriales están dirigidos principalmente a distribuciones de **Linux**. +Muchas de las cosas vistas aquí también funcionan en **macOS**, pero esto solo es _experimental_. + +### 🚀 La versión tl;dr + +1. [Instala Docker Desktop][install_docker]. + +2. (**Solo para Linux**) Asegúrate de que la cuenta de tu usuario está en el [grupo `docker`][docker group]. + +3. Prepara la `Rust` toolchain. La mayor parte se hará automáticamente durante el primer uso del archivo [rust-toolchain.toml](rust-toolchain.toml). + Todo lo que nos queda hacer a nosotros es: + + i. Si ya tienes una versión de Rust instalada: + + ```bash + cargo install cargo-binutils rustfilt + ``` + + ii. Si necesitas instalar Rust desde cero: + + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + + source $HOME/.cargo/env + cargo install cargo-binutils rustfilt + ``` + +4. En caso de que uses `Visual Studio Code`, recomiendo que instales la extensión [Rust Analyzer extension]. + +5. (**Solo para macOS**) Instala algunas `Ruby` gems. + + Ejecuta esto en la carpeta root del repositorio: + + ```bash + bundle install --path .vendor/bundle --without development + ``` + +[docker group]: https://docs.docker.com/engine/install/linux-postinstall/ +[Rust Analyzer extension]: https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer + +### 🧰 Más detalles: Eliminando Lios con Toolchains + +Esta serie trata de enfocarse lo máximo posible en tener una experiencia agradable para el usuario. +Por lo tanto, se han dirigido muchos esfuerzos a eliminar la parte más difícil del desarrollo de +los sistemas incorporados (embedded) tanto como se pudo. + +Rust por sí mismo ya ayuda mucho, porque tiene integrado el soporte para compilación cruzada. +Todo lo que necesitamos para compilar desde una máquina con una arquitectura `x86` a una Raspberry Pi +con arquitectura `AArch64` será automáticamente instalado por `rustup`. Sin embargo, además de usar +el compilador de Rust, también usaremos algunas otras herramientas, entre las cuales están: + +- `QEMU` para emular nuestro núcleo en nuestra máquina principal. +- Una herramienta llamada `Minipush` para cargar el núcleo en una Raspberry Pi cuando queramos usando `UART`. +- `OpenOCD` y `GDB` para hacer depuración ("debugging") en la máquina a instalar. + +Hay muchas cosas que pueden salir mal mientras instalamos y/o compilamos las versiones correctas de cada +herramienta en tu máquina. Por ejemplo, tu distribución de Linux tal vez podría no proporcionar las versiones más +recientes de paquetes que se necesiten. O tal vez te falten algunas dependencias para la compilar estas herramientas. + +Esta es la razón por la cual usaremos [Docker][install_docker] mientras sea posible. Te +estamos proporcionando un contenedor que tiene todas las herramientas o dependencias preinstaladas. +Si quieres saber más acerca de Docker y revisar el contenedor proporcionado, por favor revisa la carpeta +[docker](docker) del repositorio. + +[install_docker]: https://docs.docker.com/get-docker/ + +## 📟 Puerto Serie USB + +Ya que el núcleo desarrollado en este tutorial se ejecuta en hardware real, se recomienda que tengas un adaptador de puerto serie USB cable para sentir la experiencia completa. + +- Puedes encontrar estos cables que deberían funcionar sin ningún problema en [\[1\]] [\[2\]], pero + hay muchos otros que pueden funcionar. Idealmente, tu cable estaría basado en el chip `CP2102`. +- Lo conectas a los pines `GND` y `GPIO` `14/15` como se muestra en la parte inferior. +- [Tutorial 5](05_drivers_gpio_uart) es la primera vez en la que lo vas usar. Revisa las instrucciones + sobre cómo preparar una tarjeta SD para arrancar en tu núcleo desde ahí. +- Empezando con el [tutorial 6](06_uart_chainloader), arrancar núcleos en tu Raspberry Pi comienza a ser + más fácil. En este tutorial se desarrolla un `chainloader`, que será el último archivo que necesitarás + copiar de manera manual a la tarjeta SD por el momento. Esto te permitirá cargar los núcleos de los tutoriales + durante el arranque usando `UART`. + +![UART wiring diagram](doc/wiring.png) + +[\[1\]]: https://www.amazon.de/dp/B0757FQ5CX/ref=cm_sw_r_tw_dp_U_x_ozGRDbVTJAG4Q +[\[2\]]: https://www.adafruit.com/product/954 + +## 🙌 Agradecimientos + +La versión original de estos tutoriales empezó como un fork de los increíbles +[tutoriales de programación en hardware en la RPi3](https://github.com/bztsrc/raspi3-tutorial) en `C` +de [Zoltan Baldaszti](https://github.com/bztsrc). ¡Gracias por darme un punto de partida! + +### Traducciones de este repositorio + +- **Chino:** + - [@colachg] y [@readlnh]. + - Necesitan actualizaciones. +- **Español:** + - [@zanezhub]. + - En el futuro habrán tutoriales traducidos al español. + +[@colachg]: https://github.com/colachg +[@readlnh]: https://github.com/readlnh +[@zanezhub]: https://github.com/zanezhub + +## Licencia + +Este proyecto está licenciado por cualquiera de las siguientes licencias como alguna de tus dos opciones + +- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) o http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) o http://opensource.org/licenses/MIT) + +### Contribución + +A menos de que lo menciones, cualquier contribución enviada por ti para su inclusión en este trabajo, +tal como se define en la licencia Apache-2.0, deberá tener doble licencia como se muestra en la parte superior, sin ningún +cambio de términos o condiciones. diff --git a/README.md b/README.md index 5af62a962..c31b549e8 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@
- + ## ℹ️ Introduction @@ -18,14 +18,13 @@ Have fun! _Best regards,
Andre ([@andre-richter])_ -P.S.: In the future, Chinese :cn: versions of the tutorials will be maintained as -[`README.CN.md`](README.CN.md) by [@colachg] and [@readlnh]. +P.S.: For other languages, please look out for alternative README files. For example, +[`README.CN.md`](README.CN.md) or [`README.ES.md`](README.ES.md). Many thanks to our +[translators](#translations-of-this-repository) 🙌. [ARMv8-A architecture]: https://developer.arm.com/products/architecture/cpu-architecture/a-profile/docs [monolithic]: https://en.wikipedia.org/wiki/Monolithic_kernel [@andre-richter]: https://github.com/andre-richter -[@colachg]: https://github.com/colachg -[@readlnh]: https://github.com/readlnh ## 📑 Organization @@ -40,7 +39,7 @@ P.S.: In the future, Chinese :cn: versions of the tutorials will be maintained a - The code written in these tutorials supports and runs on the **Raspberry Pi 3** and the **Raspberry Pi 4**. - Tutorials 1 till 5 are groundwork code which only makes sense to run in `QEMU`. - - Starting with [tutorial 6](06_drivers_gpio_uart), you can load and run the kernel on the real + - Starting with [tutorial 5](05_drivers_gpio_uart), you can load and run the kernel on the real Raspberrys and observe output over `UART`. - Although the Raspberry Pi 3 and 4 are the main target boards, the code is written in a modular fashion which allows for easy porting to other CPU architectures and/or boards. @@ -58,55 +57,54 @@ P.S.: In the future, Chinese :cn: versions of the tutorials will be maintained a ## 🛠 System Requirements -The tutorials are primarily targeted at **Linux**-based distributions. Most stuff will also work on -other Unix flavors such as **macOS**, but this is only _experimental_. +The tutorials are primarily targeted at **Linux**-based distributions. Most stuff will also work on **macOS**, but this is only _experimental_. ### 🚀 The tl;dr Version -1. [Install Docker][install_docker]. -1. Ensure your user account is in the [docker group]. -1. Install a suitable `Rust` toolchain: +1. [Install Docker Engine][install_docker]. +1. (**Linux only**) Ensure your user account is in the [docker group]. +1. Prepare the `Rust` toolchain. Most of it will be handled on first use through the + [rust-toolchain.toml](rust-toolchain.toml) file. What's left for us to do is: 1. If you already have a version of Rust installed: ```bash - rustup toolchain add nightly-2020-11-20 - rustup default nightly-2020-11-20 - rustup component add llvm-tools-preview - rustup target add aarch64-unknown-none-softfloat cargo install cargo-binutils rustfilt ``` - 2. If you need a fresh install: + 1. If you need to install Rust from scratch: ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- \ - --default-toolchain nightly-2020-11-20 \ - --component llvm-tools-preview + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env - rustup target add aarch64-unknown-none-softfloat cargo install cargo-binutils rustfilt ``` -3. In case you use `Visual Studio Code`, I strongly recommend installing the [Rust Analyzer extension]. -4. If you are **NOT** running Linux, some `Ruby` gems are needed as well: +1. In case you use `Visual Studio Code`, I strongly recommend installing the [Rust Analyzer extension]. +1. (**macOS only**) Install a few `Ruby` gems. + + This was last tested by the author with Ruby version `3.0.2` on `macOS Monterey`. If you are using + `rbenv`, the respective `.ruby-version` file is already in place. If you never heard of `rbenv`, + try using [this little guide](https://stackoverflow.com/a/68118750). + + Run this in the repository root folder: ```bash - sudo gem install bundler - bundle config set path '.vendor/bundle' + bundle config set --local path '.vendor/bundle' + bundle config set --local without 'development' bundle install ``` [docker group]: https://docs.docker.com/engine/install/linux-postinstall/ [Rust Analyzer extension]: https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer -### 🧰 The Long Version: Eliminating Toolchain Hassle +### 🧰 More Details: Eliminating Toolchain Hassle This series tries to put a strong focus on user friendliness. Therefore, efforts were made to -eliminate the biggest painpoint in embedded development as much as possible: Toolchain hassle. +eliminate the biggest painpoint in embedded development as much as possible: `Toolchain hassle`. Rust itself is already helping a lot in that regard, because it has built-in support for cross-compilation. All that we need for cross-compiling from an `x86` host to the Raspberry Pi's -`AArch64` architecture is to install the respective target through `rustup`. However, besides the -Rust compiler, we will use some more tools. Among others: +`AArch64` architecture will be automatically installed by `rustup`. However, besides the Rust +compiler, we will use some more tools. Among others: - `QEMU` to emulate our kernel on the host system. - A self-made tool called `Minipush` to load a kernel onto the Raspberry Pi on-demand over `UART`. @@ -121,19 +119,19 @@ accompanying container that has all the needed tools or dependencies pre-install pulled in automagically once it is needed. If you want to know more about Docker and peek at the provided container, please refer to the repository's [docker](docker) folder. -[install_docker]: https://docs.docker.com/get-docker/ +[install_docker]: https://docs.docker.com/engine/install/#server ## 📟 USB Serial Output Since the kernel developed in the tutorials runs on the real hardware, it is highly recommended to -get a USB serial debug cable to get the full experience. The cable also powers the Raspberry once -you connect it, so you don't need extra power over the dedicated power-USB. +get a USB serial cable to get the full experience. -- You can find USB-to-serial cables that should work right away at [\[1\]] [\[2\]]. -- You connect it to the GPIO pins `14/15` as shown below. -- [Tutorial 6](06_drivers_gpio_uart) is the first where you can use it. Check it out for +- You can find USB-to-serial cables that should work right away at [\[1\]] [\[2\]], but many others + will work too. Ideally, your cable is based on the `CP2102` chip. +- You connect it to `GND` and GPIO pins `14/15` as shown below. +- [Tutorial 5](05_drivers_gpio_uart) is the first where you can use it. Check it out for instructions on how to prepare the SD card to boot your self-made kernel from it. -- Starting with [tutorial 7](07_uart_chainloader), booting kernels on your Raspberry is getting +- Starting with [tutorial 6](06_uart_chainloader), booting kernels on your Raspberry is getting _really_ comfortable. In this tutorial, a so-called `chainloader` is developed, which will be the last file you need to manually copy on the SD card for a while. It will enable you to load the tutorial kernels during boot on demand over `UART`. @@ -149,12 +147,25 @@ The original version of the tutorials started out as a fork of [Zoltan Baldaszti](https://github.com/bztsrc)'s awesome [tutorials on bare metal programming on RPi3](https://github.com/bztsrc/raspi3-tutorial) in `C`. Thanks for giving me a head start! +### Translations of this repository + + - **Chinese** + - [@colachg] and [@readlnh]. + - Need updating. + - **Spanish** + - [@zanezhub]. + - In the future there'll be tutorials translated to spanish. + +[@colachg]: https://github.com/colachg +[@readlnh]: https://github.com/readlnh +[@zanezhub]: https://github.com/zanezhub + ## License Licensed under either of -- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) -- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) +- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. diff --git a/X1_JTAG_boot/.vscode/settings.json b/X1_JTAG_boot/.vscode/settings.json index a0d6a9202..bfa278e9a 100644 --- a/X1_JTAG_boot/.vscode/settings.json +++ b/X1_JTAG_boot/.vscode/settings.json @@ -1,7 +1,10 @@ { - "editor.formatOnSave": true, - "editor.rulers": [100], - "rust-analyzer.checkOnSave.overrideCommand": ["make", "check"], - "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", - "rust-analyzer.cargo.features": ["bsp_rpi3"] + "editor.formatOnSave": true, + "editor.rulers": [100], + "rust-analyzer.cargo.target": "aarch64-unknown-none-softfloat", + "rust-analyzer.cargo.features": ["bsp_rpi3"], + "rust-analyzer.checkOnSave.allTargets": false, + "rust-analyzer.checkOnSave.extraArgs": ["--bins"], + "rust-analyzer.lens.debug": false, + "rust-analyzer.lens.run": false } diff --git a/X1_JTAG_boot/Cargo.lock b/X1_JTAG_boot/Cargo.lock index 102e57301..9020b4f99 100644 --- a/X1_JTAG_boot/Cargo.lock +++ b/X1_JTAG_boot/Cargo.lock @@ -1,33 +1,26 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -[[package]] -name = "cortex-a" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a389514c1229e12a03c0e8de8b357671b71e1d1bdab3a4f5b591abc94169cba8" -dependencies = [ - "register", -] +version = 3 [[package]] -name = "kernel" -version = "0.1.0" +name = "aarch64-cpu" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ - "cortex-a", - "register", + "tock-registers", ] [[package]] -name = "register" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deaba5b0e477d21f61a57504bb5cef4a1e86de30300b457d38971c1cfc98b815" +name = "mingo" +version = "0.8.0" dependencies = [ + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.5.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70323afdb8082186c0986da0e10f6e4ed103d681c921c00597e98d9806dac20f" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/X1_JTAG_boot/Cargo.toml b/X1_JTAG_boot/Cargo.toml index 8a1a364ef..e310c371e 100644 --- a/X1_JTAG_boot/Cargo.toml +++ b/X1_JTAG_boot/Cargo.toml @@ -1,17 +1,20 @@ [package] -name = "kernel" -version = "0.1.0" +name = "mingo" +version = "0.8.0" authors = ["Andre Richter "] -edition = "2018" +edition = "2021" [profile.release] lto = true -# The features section is used to select the target board. [features] default = [] -bsp_rpi3 = ["register"] -bsp_rpi4 = ["register"] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] + +[[bin]] +name = "kernel" +path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies @@ -20,9 +23,8 @@ bsp_rpi4 = ["register"] [dependencies] # Optional dependencies -register = { version = "0.5.x", optional = true } +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "4.x.x" } - +aarch64-cpu = { version = "9.x.x" } diff --git a/X1_JTAG_boot/Makefile b/X1_JTAG_boot/Makefile index 2f04337ed..b13f0dfb7 100644 --- a/X1_JTAG_boot/Makefile +++ b/X1_JTAG_boot/Makefile @@ -1,17 +1,28 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2020 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -# Default to the RPi3 +include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk + +##-------------------------------------------------------------------------------------------------- +## Optional, user-provided configuration values +##-------------------------------------------------------------------------------------------------- + +# Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 -# Query the host system's kernel name -UNAME_S = $(shell uname -s) -# BSP-specific arguments + +##-------------------------------------------------------------------------------------------------- +## BSP-specific configuration values +##-------------------------------------------------------------------------------------------------- +QEMU_MISSING_STRING = "This board is not yet supported for QEMU." + ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img @@ -20,7 +31,8 @@ ifeq ($(BSP),rpi3) QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat @@ -30,88 +42,198 @@ else ifeq ($(BSP),rpi4) QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm - LINKER_FILE = src/bsp/raspberrypi/link.ld + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif -# Export for build.rs -export LINKER_FILE +# Export for build.rs. +export LD_SCRIPT_PATH + + + +##-------------------------------------------------------------------------------------------------- +## Targets and Prerequisites +##-------------------------------------------------------------------------------------------------- +KERNEL_MANIFEST = Cargo.toml +KERNEL_LINKER_SCRIPT = kernel.ld +LAST_BUILD_CONFIG = target/$(BSP).build_config + +KERNEL_ELF = target/$(TARGET)/release/kernel +# This parses cargo's dep-info file. +# https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) -RUSTFLAGS = -C link-arg=-T$(LINKER_FILE) $(RUSTC_MISC_ARGS) -RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) -D warnings -D missing_docs + +##-------------------------------------------------------------------------------------------------- +## Command building blocks +##-------------------------------------------------------------------------------------------------- +RUSTFLAGS = $(RUSTC_MISC_ARGS) \ + -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ + -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) + +RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ + -D warnings \ + -D missing_docs + +FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ - --features bsp_$(BSP) \ + $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary -KERNEL_ELF = target/$(TARGET)/release/kernel - -DOCKER_IMAGE = rustembedded/osdev-utils -DOCKER_CMD = docker run --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i -t -DOCKER_ARG_DIR_UTILS = -v $(shell pwd)/../utils:/work/utils -DOCKER_ARG_DEV = --privileged -v /dev:/dev - -DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) -DOCKER_ELFTOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) - -# Dockerize commands that require USB device passthrough only on Linux -ifeq ($(UNAME_S),Linux) +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb + +##------------------------------------------------------------------------------ +## Dockerization +##------------------------------------------------------------------------------ +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DEV = --privileged -v /dev:/dev + +# DOCKER_IMAGE defined in include file (see top of this file). +DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) +DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_UTILS) $(DOCKER_IMAGE) + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) endif -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_MINIPUSH = ruby ../utils/minipush.rb -.PHONY: all $(KERNEL_ELF) $(KERNEL_BIN) doc qemu chainboot clippy clean readelf objdump nm check -all: $(KERNEL_BIN) +##-------------------------------------------------------------------------------------------------- +## Targets +##-------------------------------------------------------------------------------------------------- +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check -$(KERNEL_ELF): - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) +all: $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Save the configuration as a file, so make understands if it changed. +##------------------------------------------------------------------------------ +$(LAST_BUILD_CONFIG): + @rm -f target/*.build_config + @mkdir -p target + @touch $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Compile the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF): $(KERNEL_ELF_DEPS) + $(call color_header, "Compiling kernel ELF - $(BSP)") + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) + +##------------------------------------------------------------------------------ +## Generate the stripped kernel binary +##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) + $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) - + $(call color_progress_prefix, "Name") + @echo $(KERNEL_BIN) + $(call color_progress_prefix, "Size") + $(call disk_usage_KiB, $(KERNEL_BIN)) + +##------------------------------------------------------------------------------ +## Generate the documentation +##------------------------------------------------------------------------------ doc: - $(DOC_CMD) --document-private-items --open + $(call color_header, "Generating docs") + @$(DOC_CMD) --document-private-items --open + +##------------------------------------------------------------------------------ +## Run the kernel in QEMU +##------------------------------------------------------------------------------ +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. -ifeq ($(QEMU_MACHINE_TYPE),) qemu: - @echo "This board is not yet supported for QEMU." -else + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + qemu: $(KERNEL_BIN) + $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + endif +##------------------------------------------------------------------------------ +## Push the kernel to the real HW target +##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Run clippy +##------------------------------------------------------------------------------ clippy: - RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) +##------------------------------------------------------------------------------ +## Clean +##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) +##------------------------------------------------------------------------------ +## Run readelf +##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) - readelf --headers $(KERNEL_ELF) + $(call color_header, "Launching readelf") + @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) +##------------------------------------------------------------------------------ +## Run objdump +##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(OBJDUMP_BINARY) --disassemble --demangle $(KERNEL_ELF) | rustfilt - + $(call color_header, "Launching objdump") + @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ + --section .text \ + --section .rodata \ + $(KERNEL_ELF) | rustfilt + +##------------------------------------------------------------------------------ +## Run nm +##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) - @$(DOCKER_ELFTOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + -# For rust-analyzer -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff --git a/X1_JTAG_boot/build.rs b/X1_JTAG_boot/build.rs index 40ee0284d..cab00bb37 100644 --- a/X1_JTAG_boot/build.rs +++ b/X1_JTAG_boot/build.rs @@ -1,7 +1,20 @@ -use std::env; +use std::{env, fs, process}; fn main() { - let linker_file = env::var("LINKER_FILE").unwrap(); + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; - println!("cargo:rerun-if-changed={}", linker_file); + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); } diff --git a/X1_JTAG_boot/jtag_boot_rpi3.img b/X1_JTAG_boot/jtag_boot_rpi3.img index 064b41a45..f472e7666 100755 Binary files a/X1_JTAG_boot/jtag_boot_rpi3.img and b/X1_JTAG_boot/jtag_boot_rpi3.img differ diff --git a/X1_JTAG_boot/jtag_boot_rpi4.img b/X1_JTAG_boot/jtag_boot_rpi4.img index 44e2fb794..b4bca1b72 100755 Binary files a/X1_JTAG_boot/jtag_boot_rpi4.img and b/X1_JTAG_boot/jtag_boot_rpi4.img differ diff --git a/X1_JTAG_boot/src/_arch/aarch64/cpu.rs b/X1_JTAG_boot/src/_arch/aarch64/cpu.rs index 3f502ee02..602c9789c 100644 --- a/X1_JTAG_boot/src/_arch/aarch64/cpu.rs +++ b/X1_JTAG_boot/src/_arch/aarch64/cpu.rs @@ -1,37 +1,17 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. - -use crate::{bsp, cpu}; -use cortex_a::{asm, regs::*}; - -//-------------------------------------------------------------------------------------------------- -// Boot Code -//-------------------------------------------------------------------------------------------------- - -/// The entry of the `kernel` binary. -/// -/// The function must be named `_start`, because the linker is looking for this exact name. -/// -/// # Safety -/// -/// - Linker script must ensure to place this function at `0x80_000`. -#[naked] -#[no_mangle] -pub unsafe fn _start() -> ! { - use crate::runtime_init; - - // Expect the boot core to start in EL2. - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - SP.set(bsp::memory::boot_core_stack_end() as u64); - runtime_init::runtime_init() - } else { - // If not core0, infinitely wait for events. - wait_forever() - } -} +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.rs b/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.rs new file mode 100644 index 000000000..2a6c46492 --- /dev/null +++ b/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural boot code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::boot::arch_boot + +use core::arch::global_asm; + +// Assembly counterpart to this file. +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff --git a/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.s b/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.s new file mode 100644 index 000000000..78f8c321d --- /dev/null +++ b/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.s @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +.section .text._start + +//------------------------------------------------------------------------------ +// fn _start() +//------------------------------------------------------------------------------ +_start: + // Only proceed on the boot core. Park it otherwise. + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. + b _start_rust + + // Infinitely wait for events (aka "park the core"). +.L_parking_loop: + wfe + b .L_parking_loop + +.size _start, . - _start +.type _start, function +.global _start diff --git a/X1_JTAG_boot/src/_arch/aarch64/cpu/smp.rs b/X1_JTAG_boot/src/_arch/aarch64/cpu/smp.rs deleted file mode 100644 index 8429e1d2b..000000000 --- a/X1_JTAG_boot/src/_arch/aarch64/cpu/smp.rs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Architectural symmetric multiprocessing. - -use cortex_a::regs::*; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return the executing core's id. -#[inline(always)] -pub fn core_id() -> T -where - T: From, -{ - const CORE_MASK: u64 = 0b11; - - T::from((MPIDR_EL1.get() & CORE_MASK) as u8) -} diff --git a/X1_JTAG_boot/src/_arch/aarch64/time.rs b/X1_JTAG_boot/src/_arch/aarch64/time.rs index af98ddd01..eb97b8be9 100644 --- a/X1_JTAG_boot/src/_arch/aarch64/time.rs +++ b/X1_JTAG_boot/src/_arch/aarch64/time.rs @@ -1,98 +1,164 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural timer primitives. - -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::regs::*; +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +#[cfg(feature = "bsp_rpi3")] +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- -const NS_PER_S: u64 = 1_000_000_000; +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); -/// ARMv8 Generic Timer. -struct GenericTimer; +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- -static TIME_MANAGER: GenericTimer = GenericTimer; +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); } -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ +impl Add for GenericTimerCounterValue { + type Output = Self; -impl time::interface::TimeManager for GenericTimer { - fn resolution(&self) -> Duration { - Duration::from_nanos(NS_PER_S / (CNTFRQ_EL0.get() as u64)) + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); - fn uptime(&self) -> Duration { - let frq: u64 = CNTFRQ_EL0.get() as u64; - let current_count: u64 = CNTPCT_EL0.get() * NS_PER_S; + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); - Duration::from_nanos(current_count / frq) + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 % frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) } +} - fn spin_for(&self, duration: Duration) { - // Instantly return on zero. - if duration.as_nanos() == 0 { - return; - } +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} - // Calculate the register compare value. - let frq = CNTFRQ_EL0.get() as u64; - let x = match frq.checked_mul(duration.as_nanos() as u64) { - None => { - warn!("Spin duration too long, skipping"); - return; - } - Some(val) => val, - }; - let tval = x / NS_PER_S; - - // Check if it is within supported bounds. - let warn: Option<&str> = if tval == 0 { - Some("smaller") - // The upper 32 bits of CNTP_TVAL_EL0 are reserved. - } else if tval > u32::max_value().into() { - Some("bigger") - } else { - None - }; - - if let Some(w) = warn { - warn!( - "Spin duration {} than architecturally supported, skipping", - w - ); - return; +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); } - // Set the compare value register. - CNTP_TVAL_EL0.set(tval); + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } - // Kick off the counting. // Disable timer interrupt. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::SET + CNTP_CTL_EL0::IMASK::SET); + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); - // ISTATUS will be '1' when cval ticks have passed. Busy-check it. - while !CNTP_CTL_EL0.matches_all(CNTP_CTL_EL0::ISTATUS::SET) {} + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); - // Disable counting again. - CNTP_CTL_EL0.modify(CNTP_CTL_EL0::ENABLE::CLEAR); + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) } } + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +#[cfg(feature = "bsp_rpi3")] +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff --git a/X1_JTAG_boot/src/bsp.rs b/X1_JTAG_boot/src/bsp.rs index 3a5657ade..246973bc0 100644 --- a/X1_JTAG_boot/src/bsp.rs +++ b/X1_JTAG_boot/src/bsp.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter -//! Conditional re-exporting of Board Support Packages. +//! Conditional reexporting of Board Support Packages. mod device_driver; diff --git a/X1_JTAG_boot/src/bsp/device_driver.rs b/X1_JTAG_boot/src/bsp/device_driver.rs index ce7396f22..64049a4cf 100644 --- a/X1_JTAG_boot/src/bsp/device_driver.rs +++ b/X1_JTAG_boot/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/X1_JTAG_boot/src/bsp/device_driver/bcm.rs b/X1_JTAG_boot/src/bsp/device_driver/bcm.rs index 59071d5d8..1c343d1d7 100644 --- a/X1_JTAG_boot/src/bsp/device_driver/bcm.rs +++ b/X1_JTAG_boot/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. diff --git a/X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs index 15bd3b78b..8e57dfedb 100644 --- a/X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ b/X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -8,7 +8,11 @@ use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; -use register::{mmio::*, register_bitfields, register_structs}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -104,16 +108,13 @@ register_structs! { /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -pub struct GPIOInner { +struct GPIOInner { registers: Registers, } -// Export the inner struct so that BSPs can use it for the panic handler. -pub use GPIOInner as PanicGPIO; +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { @@ -121,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -139,7 +140,7 @@ impl GPIOInner { /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { - use crate::{time, time::interface::TimeManager}; + use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. @@ -185,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -210,6 +217,6 @@ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { - "BCM GPIO" + Self::COMPATIBLE } } diff --git a/X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs index e39bc7cdb..d92612ea8 100644 --- a/X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ b/X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -1,15 +1,24 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; -use register::{mmio::*, register_bitfields, register_structs}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -17,52 +26,60 @@ use register::{mmio::*, register_bitfields, register_structs}; // PL011 UART registers. // -// Descriptions taken from -// https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, - /// Flag Register + /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// Line Control Register, UARTLCR_ LCRH. + /// Line Control Register, LCR_H. /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is empty. If - /// the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does - /// not indicate if there is data in the transmit shift register. + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_ LCRH Register. + /// LCR_H Register. /// - /// If the FIFO is disabled, this bit is set when the transmit holding register is full. If - /// the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the - /// UARTLCR_H Register. + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. /// - /// If the FIFO is disabled, this bit is set when the receive holding register is empty. If - /// the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. - RXFE OFFSET(4) NUMBITS(1) [] + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] ], - /// Integer Baud rate divisor + /// Integer Baud Rate Divisor. IBRD [ - /// Integer Baud rate divisor - IBRD OFFSET(0) NUMBITS(16) [] + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], - /// Fractional Baud rate divisor + /// Fractional Baud Rate Divisor. FBRD [ - /// Fractional Baud rate divisor - FBRD OFFSET(0) NUMBITS(6) [] + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], - /// Line Control register - LCRH [ + /// Line Control Register. + LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. + #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, @@ -73,34 +90,42 @@ register_bitfields! { /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding - /// registers + /// registers. /// - /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], - /// Control Register + /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. - /// Data reception occurs for UART signals. When the UART is disabled in the middle of - /// reception, it completes the current character before stopping. - RXE OFFSET(9) NUMBITS(1) [ + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. - /// Data transmission occurs for UART signals. When the UART is disabled in the middle of - /// transmission, it completes the current character before stopping. - TXE OFFSET(8) NUMBITS(1) [ + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], - /// UART enable + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. @@ -109,9 +134,9 @@ register_bitfields! { ] ], - /// Interrupt Clear Register + /// Interrupt Clear Register. ICR [ - /// Meta field for all pending interrupts + /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } @@ -125,7 +150,7 @@ register_structs! { (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), - (0x2c => LCRH: WriteOnly), + (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), @@ -136,18 +161,21 @@ register_structs! { /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} -pub struct PL011UartInner { +struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } -// Export the inner struct so that BSPs can use it for the panic handler. -pub use PL011UartInner as PanicUart; +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { @@ -155,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -174,22 +202,52 @@ impl PL011UartInner { /// Set up baud rate and characteristics. /// - /// The calculation for the BRD given a target rate of 2300400 and a clock set to 48 MHz is: - /// `(48_000_000/16)/230400 = 13,02083`. `13` goes to the `IBRD` (integer field). The `FBRD` - /// (fractional field) is only 6 bits so `0,0208*64 = 1,3312 rounded to 1` will give the best - /// approximation we can get. A 5 % error margin is acceptable for UART and we're now at 0,01 %. + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// - /// This results in 8N1 and 230400 baud (we set the clock to 48 MHz in config.txt). + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { - // Turn it off temporarily. + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. self.registers.CR.set(0); + // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); - self.registers.IBRD.write(IBRD::IBRD.val(13)); - self.registers.FBRD.write(FBRD::FBRD.val(1)); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers - .LCRH - .write(LCRH::WLEN::EightBit + LCRH::FEN::FifosEnabled); // 8N1 + Fifo on + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); @@ -207,6 +265,43 @@ impl PL011UartInner { self.chars_written += 1; } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are @@ -228,7 +323,15 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. @@ -246,7 +349,7 @@ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { - "BCM PL011 UART" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { @@ -264,51 +367,30 @@ impl console::interface::Write for PL011Uart { } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write:fmt()` to increase + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. - self.inner.lock(|inner| { - while !inner.registers.FR.matches_all(FR::TXFE::SET) { - cpu::nop(); - } - }); + self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { - self.inner.lock(|inner| { - // Spin while RX FIFO empty is set. - while inner.registers.FR.matches_all(FR::RXFE::SET) { - cpu::nop(); - } - - // Read one character. - let mut ret = inner.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } - - // Update statistics. - inner.chars_read += 1; - - ret - }) + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } - fn clear(&self) { - self.inner.lock(|inner| { - // Read from the RX FIFO until it is indicating empty. - while !inner.registers.FR.matches_all(FR::RXFE::SET) { - inner.registers.DR.get(); - } - }) + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} } } @@ -321,3 +403,5 @@ impl console::interface::Statistics for PL011Uart { self.inner.lock(|inner| inner.chars_read) } } + +impl console::interface::All for PL011Uart {} diff --git a/X1_JTAG_boot/src/bsp/device_driver/common.rs b/X1_JTAG_boot/src/bsp/device_driver/common.rs index cd2c07601..dfe7d8ef3 100644 --- a/X1_JTAG_boot/src/bsp/device_driver/common.rs +++ b/X1_JTAG_boot/src/bsp/device_driver/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/X1_JTAG_boot/src/bsp/raspberrypi.rs b/X1_JTAG_boot/src/bsp/raspberrypi.rs index a4a812327..b6d48fddc 100644 --- a/X1_JTAG_boot/src/bsp/raspberrypi.rs +++ b/X1_JTAG_boot/src/bsp/raspberrypi.rs @@ -1,21 +1,9 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. -pub mod console; pub mod cpu; pub mod driver; pub mod memory; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- -use super::device_driver; - -static GPIO: device_driver::GPIO = - unsafe { device_driver::GPIO::new(memory::map::mmio::GPIO_START) }; - -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(memory::map::mmio::PL011_UART_START) }; diff --git a/X1_JTAG_boot/src/bsp/raspberrypi/console.rs b/X1_JTAG_boot/src/bsp/raspberrypi/console.rs deleted file mode 100644 index d1b60dd82..000000000 --- a/X1_JTAG_boot/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// In case of a panic, the panic handler uses this function to take a last shot at printing -/// something before the system is halted. -/// -/// We try to init panic-versions of the GPIO and the UART. The panic versions are not protected -/// with synchronization primitives, which increases chances that we get to print something, even -/// when the kernel's default GPIO or UART instances happen to be locked at the time of the panic. -/// -/// # Safety -/// -/// - Use only for printing during a panic. -pub unsafe fn panic_console_out() -> impl fmt::Write { - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START); - let mut panic_uart = device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START); - - panic_gpio.map_pl011_uart(); - panic_uart.init(); - panic_uart -} - -/// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -} diff --git a/X1_JTAG_boot/src/bsp/raspberrypi/cpu.rs b/X1_JTAG_boot/src/bsp/raspberrypi/cpu.rs index 8410a9615..65cf5abbe 100644 --- a/X1_JTAG_boot/src/bsp/raspberrypi/cpu.rs +++ b/X1_JTAG_boot/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. @@ -9,4 +9,6 @@ //-------------------------------------------------------------------------------------------------- /// Used by `arch` code to find the early boot core. -pub const BOOT_CORE_ID: usize = 0; +#[no_mangle] +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; diff --git a/X1_JTAG_boot/src/bsp/raspberrypi/driver.rs b/X1_JTAG_boot/src/bsp/raspberrypi/driver.rs index fe24dd71b..2a80ee2c5 100644 --- a/X1_JTAG_boot/src/bsp/raspberrypi/driver.rs +++ b/X1_JTAG_boot/src/bsp/raspberrypi/driver.rs @@ -1,49 +1,71 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP driver support. -use crate::driver; +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; //-------------------------------------------------------------------------------------------------- -// Private Definitions +// Global instances //-------------------------------------------------------------------------------------------------- -/// Device Driver Manager type. -struct BSPDriverManager { - device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -} +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; //-------------------------------------------------------------------------------------------------- -// Global instances +// Private Code //-------------------------------------------------------------------------------------------------- -static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { - device_drivers: [&super::GPIO, &super::PL011_UART], -}; +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- + Ok(()) +} -/// Return a reference to the driver manager. -pub fn driver_manager() -> &'static impl driver::interface::DriverManager { - &BSP_DRIVER_MANAGER +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) } -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use driver::interface::DeviceDriver; +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); -impl driver::interface::DriverManager for BSPDriverManager { - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { - &self.device_drivers[..] - } + Ok(()) +} - fn post_device_driver_init(&self) { - // Configure PL011Uart's output pins. - super::GPIO.map_pl011_uart(); +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) } diff --git a/X1_JTAG_boot/src/bsp/raspberrypi/kernel.ld b/X1_JTAG_boot/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 000000000..32f6defa1 --- /dev/null +++ b/X1_JTAG_boot/src/bsp/raspberrypi/kernel.ld @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT OR Apache-2.0 + * + * Copyright (c) 2018-2023 Andre Richter + */ + +__rpi_phys_dram_start_addr = 0; + +/* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ +__rpi_phys_binary_load_addr = 0x80000; + + +ENTRY(__rpi_phys_binary_load_addr) + +/* Flags: + * 4 == R + * 5 == RX + * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. + */ +PHDRS +{ + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); +} + +SECTIONS +{ + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + + /*********************************************************************************************** + * Code + RO Data + Global Offset Table + ***********************************************************************************************/ + .text : + { + KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ + } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } +} diff --git a/X1_JTAG_boot/src/bsp/raspberrypi/link.ld b/X1_JTAG_boot/src/bsp/raspberrypi/link.ld deleted file mode 100644 index c03bb5e54..000000000 --- a/X1_JTAG_boot/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,39 +0,0 @@ -/* SPDX-License-Identifier: MIT OR Apache-2.0 - * - * Copyright (c) 2018-2020 Andre Richter - */ - -SECTIONS -{ - /* Set current address to the value from which the RPi starts execution */ - . = 0x80000; - - .text : - { - *(.text._start) *(.text*) - } - - .rodata : - { - *(.rodata*) - } - - .data : - { - *(.data*) - } - - /* Section is zeroed in u64 chunks, align start and end to 8 bytes */ - .bss ALIGN(8): - { - __bss_start = .; - *(.bss*); - . = ALIGN(8); - - /* Fill for the bss == 0 case, so that __bss_start <= __bss_end_inclusive holds */ - . += 8; - __bss_end_inclusive = . - 8; - } - - /DISCARD/ : { *(.comment*) } -} diff --git a/X1_JTAG_boot/src/bsp/raspberrypi/memory.rs b/X1_JTAG_boot/src/bsp/raspberrypi/memory.rs index fae051257..cdca14b8a 100644 --- a/X1_JTAG_boot/src/bsp/raspberrypi/memory.rs +++ b/X1_JTAG_boot/src/bsp/raspberrypi/memory.rs @@ -1,29 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. -use core::{cell::UnsafeCell, ops::RangeInclusive}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -// Symbols from the linker script. -extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_inclusive: UnsafeCell; -} - //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- -/// The board's memory map. +/// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { - pub const BOOT_CORE_STACK_END: usize = 0x8_0000; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; @@ -48,29 +35,3 @@ pub(super) mod map { pub const PL011_UART_START: usize = START + UART_OFFSET; } } - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Exclusive end address of the boot core's stack. -#[inline(always)] -pub fn boot_core_stack_end() -> usize { - map::BOOT_CORE_STACK_END -} - -/// Return the inclusive range spanning the .bss section. -/// -/// # Safety -/// -/// - Values are provided by the linker script and must be trusted as-is. -/// - The linker-provided addresses must be u64 aligned. -pub fn bss_range_inclusive() -> RangeInclusive<*mut u64> { - let range; - unsafe { - range = RangeInclusive::new(__bss_start.get(), __bss_end_inclusive.get()); - } - assert!(!range.is_empty()); - - range -} diff --git a/X1_JTAG_boot/src/console.rs b/X1_JTAG_boot/src/console.rs index e6323a20d..a83f86fe0 100644 --- a/X1_JTAG_boot/src/console.rs +++ b/X1_JTAG_boot/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -20,8 +24,7 @@ pub mod interface { /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - /// Block execution until the last character has been physically put on the TX wire - /// (draining TX buffers/FIFOs, if any). + /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } @@ -33,7 +36,7 @@ pub mod interface { } /// Clear RX buffers, if any. - fn clear(&self); + fn clear_rx(&self); } /// Console statistics. @@ -50,5 +53,29 @@ pub mod interface { } /// Trait alias for a full-fledged console. - pub trait All = Write + Read + Statistics; + pub trait All: Write + Read + Statistics {} +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} + +/// Return a reference to the currently registered console. +/// +/// This is the global console used by all printing macros. +pub fn console() -> &'static dyn interface::All { + CUR_CONSOLE.lock(|con| *con) } diff --git a/X1_JTAG_boot/src/console/null_console.rs b/X1_JTAG_boot/src/console/null_console.rs new file mode 100644 index 000000000..e92a022b6 --- /dev/null +++ b/X1_JTAG_boot/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff --git a/X1_JTAG_boot/src/cpu.rs b/X1_JTAG_boot/src/cpu.rs index 9c67c0e7d..67ab79c08 100644 --- a/X1_JTAG_boot/src/cpu.rs +++ b/X1_JTAG_boot/src/cpu.rs @@ -1,12 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; -pub use arch_cpu::*; -pub mod smp; +mod boot; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_cpu::{nop, wait_forever}; diff --git a/X1_JTAG_boot/src/cpu/boot.rs b/X1_JTAG_boot/src/cpu/boot.rs new file mode 100644 index 000000000..b1e98328a --- /dev/null +++ b/X1_JTAG_boot/src/cpu/boot.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Boot code. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/boot.rs"] +mod arch_boot; diff --git a/X1_JTAG_boot/src/cpu/smp.rs b/X1_JTAG_boot/src/cpu/smp.rs deleted file mode 100644 index b1428884d..000000000 --- a/X1_JTAG_boot/src/cpu/smp.rs +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Symmetric multiprocessing. - -#[cfg(target_arch = "aarch64")] -#[path = "../_arch/aarch64/cpu/smp.rs"] -mod arch_cpu_smp; -pub use arch_cpu_smp::*; diff --git a/X1_JTAG_boot/src/driver.rs b/X1_JTAG_boot/src/driver.rs index e2875b876..53592c66b 100644 --- a/X1_JTAG_boot/src/driver.rs +++ b/X1_JTAG_boot/src/driver.rs @@ -1,9 +1,22 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Driver support. +use crate::synchronization::{interface::Mutex, NullLock}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -24,21 +37,118 @@ pub mod interface { Ok(()) } } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; - /// Device driver management functions. +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. /// - /// The `BSP` is supposed to supply one global instance. - pub trait DriverManager { - /// Return a slice of references to all `BSP`-instantiated drivers. - /// - /// # Safety - /// - /// - The order of devices is the order in which `DeviceDriver::init()` is called. - fn all_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)]; + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } - /// Initialization code that runs after driver init. - /// - /// For example, device driver code that depends on other drivers already being online. - fn post_device_driver_init(&self); + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); } } diff --git a/X1_JTAG_boot/src/main.rs b/X1_JTAG_boot/src/main.rs index 85db786de..7ab191f5c 100644 --- a/X1_JTAG_boot/src/main.rs +++ b/X1_JTAG_boot/src/main.rs @@ -1,22 +1,14 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] //! The `kernel` binary. //! -//! # TL;DR - Overview of important Kernel entities -//! -//! - [`bsp::console::console()`] - Returns a reference to the kernel's [console interface]. -//! - [`bsp::driver::driver_manager()`] - Returns a reference to the kernel's [driver interface]. -//! - [`time::time_manager()`] - Returns a reference to the kernel's [timer interface]. -//! -//! [console interface]: ../libkernel/console/interface/index.html -//! [driver interface]: ../libkernel/driver/interface/trait.DriverManager.html -//! [timer interface]: ../libkernel/time/interface/trait.TimeManager.html -//! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the @@ -30,15 +22,22 @@ //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, -//! architectural code that belongs to the `kernel`'s memory subsystem (`src/memory.rs`) would go -//! into `src/_arch/aarch64/memory.rs`. The latter file is directly included and re-exported in -//! `src/memory.rs`, so that the architectural code parts are transparent with respect to the code's -//! module organization. That means a public function `foo()` defined in -//! `src/_arch/aarch64/memory.rs` would be reachable as `crate::memory::foo()` only. +//! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go +//! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in +//! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic +//! module's name prefixed with `arch_`. +//! +//! For example, this is the top of `src/memory/mmu.rs`: +//! +//! ``` +//! #[cfg(target_arch = "aarch64")] +//! #[path = "../_arch/aarch64/memory/mmu.rs"] +//! mod arch_mmu; +//! ``` //! -//! The `_` in `_arch` denotes that this folder is not part of the standard module hierarchy. -//! Rather, it's contents are conditionally pulled into respective files using the `#[path = -//! "_arch/xxx/yyy.rs"]` attribute. +//! Often times, items from the `arch_ module` will be publicly reexported by the parent module. +//! This way, each architecture specific module can provide its implementation of an item, while the +//! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! @@ -47,9 +46,8 @@ //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the -//! `kernel`'s subsystem modules, but there is no transparent re-exporting this time. That means -//! whatever is provided must be called starting from the `bsp` namespace, e.g. -//! `bsp::driver::driver_manager()`. +//! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is +//! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! @@ -101,26 +99,30 @@ //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` +//! +//! # Boot flow +//! +//! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. +//! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +//! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. -#![feature(const_fn_fn_ptr_basics)] +#![allow(clippy::upper_case_acronyms)] +#![feature(asm_const)] +#![feature(const_option)] #![feature(format_args_nl)] -#![feature(naked_functions)] +#![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] +#![feature(unchecked_math)] #![no_main] #![no_std] -// `mod cpu` provides the `_start()` function, the first function to run. `_start()` then calls -// `runtime_init()`, which jumps to `kernel_init()`. - mod bsp; mod console; mod cpu; mod driver; -mod memory; mod panic_wait; mod print; -mod runtime_init; mod synchronization; mod time; @@ -131,14 +133,13 @@ mod time; /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order. unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { - panic!("Error loading driver: {}: {}", i.compatible(), x); - } + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); } - bsp::driver::driver_manager().post_device_driver_init(); + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. diff --git a/X1_JTAG_boot/src/memory.rs b/X1_JTAG_boot/src/memory.rs deleted file mode 100644 index 827b8b850..000000000 --- a/X1_JTAG_boot/src/memory.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Memory Management. - -use core::ops::RangeInclusive; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out an inclusive memory range. -/// -/// # Safety -/// -/// - `range.start` and `range.end` must be valid. -/// - `range.start` and `range.end` must be `T` aligned. -pub unsafe fn zero_volatile(range: RangeInclusive<*mut T>) -where - T: From, -{ - let mut ptr = *range.start(); - let end_inclusive = *range.end(); - - while ptr <= end_inclusive { - core::ptr::write_volatile(ptr, T::from(0)); - ptr = ptr.offset(1); - } -} diff --git a/X1_JTAG_boot/src/panic_wait.rs b/X1_JTAG_boot/src/panic_wait.rs index 1386e1e23..5776aca87 100644 --- a/X1_JTAG_boot/src/panic_wait.rs +++ b/X1_JTAG_boot/src/panic_wait.rs @@ -1,39 +1,67 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. -use crate::{bsp, cpu}; -use core::{fmt, panic::PanicInfo}; +use crate::{cpu, println}; +use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -fn _panic_print(args: fmt::Arguments) { - use fmt::Write; +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { - if let Some(args) = info.message() { - panic_println!("\nKernel panic: {}", args); - } else { - panic_println!("\nKernel panic!"); - } + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let timestamp = crate::time::time_manager().uptime(); + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "[ {:>3}.{:06}] Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + timestamp.as_secs(), + timestamp.subsec_micros(), + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); cpu::wait_forever() } diff --git a/X1_JTAG_boot/src/print.rs b/X1_JTAG_boot/src/print.rs index 8b6f3f988..8e3030466 100644 --- a/X1_JTAG_boot/src/print.rs +++ b/X1_JTAG_boot/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2020 Andre Richter +// Copyright (c) 2018-2023 Andre Richter -//! Printing facilities. +//! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,14 +13,12 @@ use core::fmt; #[doc(hidden)] pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - - bsp::console::console().write_fmt(args).unwrap(); + console::console().write_fmt(args).unwrap(); } /// Prints without a newline. /// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html +/// Carbon copy from #[macro_export] macro_rules! print { ($($arg:tt)*) => ($crate::print::_print(format_args!($($arg)*))); @@ -28,7 +26,7 @@ macro_rules! print { /// Prints with a newline. /// -/// Carbon copy from https://doc.rust-lang.org/src/std/macros.rs.html +/// Carbon copy from #[macro_export] macro_rules! println { () => ($crate::print!("\n")); @@ -41,31 +39,21 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $string), + concat!("[ {:>3}.{:06}] ", $string), timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 + timestamp.subsec_micros(), )); }); ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); $crate::print::_print(format_args_nl!( - concat!("[ {:>3}.{:03}{:03}] ", $format_string), + concat!("[ {:>3}.{:06}] ", $format_string), timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, + timestamp.subsec_micros(), $($arg)* )); }) @@ -75,31 +63,21 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $string), + concat!("[W {:>3}.{:06}] ", $string), timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000 + timestamp.subsec_micros(), )); }); ($format_string:expr, $($arg:tt)*) => ({ - #[allow(unused_imports)] - use crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); - let timestamp_subsec_us = timestamp.subsec_micros(); $crate::print::_print(format_args_nl!( - concat!("[W {:>3}.{:03}{:03}] ", $format_string), + concat!("[W {:>3}.{:06}] ", $format_string), timestamp.as_secs(), - timestamp_subsec_us / 1_000, - timestamp_subsec_us % 1_000, + timestamp.subsec_micros(), $($arg)* )); }) diff --git a/X1_JTAG_boot/src/runtime_init.rs b/X1_JTAG_boot/src/runtime_init.rs deleted file mode 100644 index 9de285958..000000000 --- a/X1_JTAG_boot/src/runtime_init.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2020 Andre Richter - -//! Rust runtime initialization code. - -use crate::{bsp, memory}; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -/// Zero out the .bss section. -/// -/// # Safety -/// -/// - Must only be called pre `kernel_init()`. -#[inline(always)] -unsafe fn zero_bss() { - memory::zero_volatile(bsp::memory::bss_range_inclusive()); -} - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Equivalent to `crt0` or `c0` code in C/C++ world. Clears the `bss` section, then jumps to kernel -/// init code. -/// -/// # Safety -/// -/// - Only a single core must be active and running this function. -pub unsafe fn runtime_init() -> ! { - zero_bss(); - - crate::kernel_init() -} diff --git a/X1_JTAG_boot/src/synchronization.rs b/X1_JTAG_boot/src/synchronization.rs index 6de32807c..94c83de1c 100644 --- a/X1_JTAG_boot/src/synchronization.rs +++ b/X1_JTAG_boot/src/synchronization.rs @@ -1,13 +1,14 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! -//! Suggested literature: -//! - https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html -//! - https://stackoverflow.com/questions/59428096/understanding-the-send-trait -//! - https://doc.rust-lang.org/std/cell/index.html +//! # Resources +//! +//! - +//! - +//! - use core::cell::UnsafeCell; @@ -25,7 +26,7 @@ pub mod interface { type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } @@ -66,7 +67,7 @@ impl NullLock { impl interface::Mutex for NullLock { type Data = T; - fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; diff --git a/X1_JTAG_boot/src/time.rs b/X1_JTAG_boot/src/time.rs index cd3ceec33..19a48a885 100644 --- a/X1_JTAG_boot/src/time.rs +++ b/X1_JTAG_boot/src/time.rs @@ -1,35 +1,53 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Timer primitives. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/time.rs"] mod arch_time; -pub use arch_time::*; + +use core::time::Duration; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} - /// Time management functions. +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The uptime since power-on of the device. /// - /// The `BSP` is supposed to supply one global instance. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; - - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; - - /// Spin for a given duration. - fn spin_for(&self, duration: Duration); + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + #[cfg(feature = "bsp_rpi3")] + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) } } diff --git a/X1_JTAG_boot/tests/boot_test_string.rb b/X1_JTAG_boot/tests/boot_test_string.rb new file mode 100644 index 000000000..029dbd068 --- /dev/null +++ b/X1_JTAG_boot/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Please connect over JTAG now' diff --git a/common/docker.mk b/common/docker.mk new file mode 100644 index 000000000..61355768f --- /dev/null +++ b/common/docker.mk @@ -0,0 +1 @@ +DOCKER_IMAGE := rustembedded/osdev-utils:2021.12 diff --git a/common/format.mk b/common/format.mk new file mode 100644 index 000000000..e392304ad --- /dev/null +++ b/common/format.mk @@ -0,0 +1,12 @@ +define color_header + @tput setaf 6 2> /dev/null || true + @printf '\n%s\n' $(1) + @tput sgr0 2> /dev/null || true +endef + +define color_progress_prefix + @tput setaf 2 2> /dev/null || true + @tput bold 2 2> /dev/null || true + @printf '%12s ' $(1) + @tput sgr0 2> /dev/null || true +endef diff --git a/common/operating_system.mk b/common/operating_system.mk new file mode 100644 index 000000000..90172f775 --- /dev/null +++ b/common/operating_system.mk @@ -0,0 +1,9 @@ +ifeq ($(shell uname -s),Linux) + DU_ARGUMENTS = --block-size=1024 --apparent-size +else ifeq ($(shell uname -s),Darwin) + DU_ARGUMENTS = -k -A +endif + +define disk_usage_KiB + @printf '%s KiB\n' `du $(DU_ARGUMENTS) $(1) | cut -f1` +endef diff --git a/common/serial/minipush.rb b/common/serial/minipush.rb new file mode 100755 index 000000000..2b90dd71d --- /dev/null +++ b/common/serial/minipush.rb @@ -0,0 +1,131 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2020-2023 Andre Richter + +require_relative 'miniterm' +require 'ruby-progressbar' +require_relative 'minipush/progressbar_patch' +require 'timeout' + +class ProtocolError < StandardError; end + +# The main class +class MiniPush < MiniTerm + def initialize(serial_name, payload_path) + super(serial_name) + + @name_short = 'MP' # override + @payload_path = payload_path + @payload_size = nil + @payload_data = nil + end + + private + + # The three characters signaling the request token form the consecutive sequence "\x03\x03\x03". + def wait_for_payload_request + puts "[#{@name_short}] 🔌 Please power the target now" + + # Timeout for the request token starts after the first sign of life was received. + received = @target_serial.readpartial(4096) + Timeout.timeout(10) do + count = 0 + + loop do + raise ProtocolError if received.nil? + + received.chars.each do |c| + if c == "\u{3}" + count += 1 + return true if count == 3 + else + # A normal character resets token counting. + count = 0 + + print c + end + end + + received = @target_serial.readpartial(4096) + end + end + end + + def load_payload + @payload_size = File.size(@payload_path) + @payload_data = File.binread(@payload_path) + end + + def send_size + @target_serial.print([@payload_size].pack('L<')) + raise ProtocolError if @target_serial.read(2) != 'OK' + end + + def send_payload + pb = ProgressBar.create( + total: @payload_size, + format: "[#{@name_short}] ⏩ Pushing %k KiB %b🦀%i %p%% %r KiB/s %a", + rate_scale: ->(rate) { rate / 1024 }, + length: 92, + output: $stdout + ) + + # Send in 512 byte chunks. + while pb.progress < pb.total + part = @payload_data.slice(pb.progress, 512) + pb.progress += @target_serial.write(part) + end + end + + # override + def handle_reconnect(_error) + connection_reset + + puts + puts "[#{@name_short}] ⚡ " \ + "#{'Connection or protocol Error: '.light_red}" \ + "#{'Remove power and USB serial. Reinsert serial first, then power'.light_red}" + sleep(1) while serial_connected? + end + + public + + # override + def run + open_serial + wait_for_payload_request + load_payload + send_size + send_payload + terminal + rescue ConnectionError, EOFError, Errno::EIO, ProtocolError, Timeout::Error => e + handle_reconnect(e) + retry + rescue StandardError => e + handle_unexpected(e) + ensure + connection_reset + puts + puts "[#{@name_short}] Bye 👋" + end +end + +## ------------------------------------------------------------------------------------------------- +## Execution starts here +## ------------------------------------------------------------------------------------------------- +if __FILE__ == $PROGRAM_NAME + puts + puts 'Minipush 1.0'.cyan + puts + + # CTRL + C handler. Only here to suppress Ruby's default exception print. + trap('INT') do + # The `ensure` block from `MiniPush::run` will run after exit, restoring console state. + exit + end + + MiniPush.new(ARGV[0], ARGV[1]).run +end diff --git a/utils/minipush/progressbar_patch.rb b/common/serial/minipush/progressbar_patch.rb similarity index 91% rename from utils/minipush/progressbar_patch.rb rename to common/serial/minipush/progressbar_patch.rb index 734540646..e90b9bd14 100644 --- a/utils/minipush/progressbar_patch.rb +++ b/common/serial/minipush/progressbar_patch.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2020 Andre Richter +# Copyright (c) 2020-2023 Andre Richter # Monkey-patch ruby-progressbar so that it supports reporting the progress in KiB instead of Byte. diff --git a/utils/miniterm.rb b/common/serial/miniterm.rb similarity index 77% rename from utils/miniterm.rb rename to common/serial/miniterm.rb index fb05189ae..db2ddac5f 100755 --- a/utils/miniterm.rb +++ b/common/serial/miniterm.rb @@ -3,14 +3,17 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2020 Andre Richter +# Copyright (c) 2020-2023 Andre Richter require 'rubygems' require 'bundler/setup' -require 'io/console' + require 'colorize' +require 'io/console' require 'serialport' +SERIAL_BAUD = 921_600 + class ConnectionError < StandardError; end # The main class @@ -29,28 +32,27 @@ def serial_connected? end def wait_for_serial - loop do - break if serial_connected? + return if serial_connected? - print "\r[#{@name_short}] ⏳ Waiting for #{@target_serial_name}" + puts "[#{@name_short}] ⏳ Waiting for #{@target_serial_name}" + loop do sleep(1) + break if serial_connected? end end def open_serial wait_for_serial - @target_serial = SerialPort.new(@target_serial_name, 230_400, 8, 1, SerialPort::NONE) + @target_serial = SerialPort.new(@target_serial_name, SERIAL_BAUD, 8, 1, SerialPort::NONE) # Ensure all output is immediately flushed to the device. @target_serial.sync = true rescue Errno::EACCES => e - puts puts "[#{@name_short}] 🚫 #{e.message} - Maybe try with 'sudo'" exit else - puts - puts "[#{@name_short}] ✅ Connected" + puts "[#{@name_short}] ✅ Serial connected" end def terminal @@ -86,22 +88,22 @@ def terminal end end - def connetion_reset + def connection_reset @target_serial&.close @target_serial = nil @host_console.cooked! end # When the serial lost power or was removed during R/W operation. - def handle_reconnect - connetion_reset + def handle_reconnect(_error) + connection_reset puts puts "[#{@name_short}] ⚡ #{'Connection Error: Reinsert the USB serial again'.light_red}" end def handle_unexpected(error) - connetion_reset + connection_reset puts puts "[#{@name_short}] ⚡ #{"Unexpected Error: #{error.inspect}".light_red}" @@ -112,19 +114,23 @@ def handle_unexpected(error) def run open_serial terminal - rescue ConnectionError, EOFError, Errno::EIO - handle_reconnect + rescue ConnectionError, EOFError, Errno::EIO => e + handle_reconnect(e) retry rescue StandardError => e handle_unexpected(e) ensure - connetion_reset + connection_reset puts puts "[#{@name_short}] Bye 👋" end end +## ------------------------------------------------------------------------------------------------- +## Execution starts here +## ------------------------------------------------------------------------------------------------- if __FILE__ == $PROGRAM_NAME + puts puts 'Miniterm 1.0'.cyan puts diff --git a/common/tests/boot_test.rb b/common/tests/boot_test.rb new file mode 100644 index 000000000..5885c7272 --- /dev/null +++ b/common/tests/boot_test.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require_relative 'console_io_test' + +# Wait for an expected print during boot. +class ExpectedBootPrintTest < SubtestBase + def initialize(expected_print) + super() + @expected_print = expected_print + end + + def name + "Checking for the string: '#{@expected_print}'" + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, @expected_print) + end +end + +# Check for an expected string when booting the kernel in QEMU. +class BootTest < ConsoleIOTest + def initialize(qemu_cmd, expected_print) + subtests = [ExpectedBootPrintTest.new(expected_print)] + + super(qemu_cmd, 'Boot test', subtests) + end +end diff --git a/common/tests/console_io_test.rb b/common/tests/console_io_test.rb new file mode 100644 index 000000000..ea9d93e2d --- /dev/null +++ b/common/tests/console_io_test.rb @@ -0,0 +1,117 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'expect' +require 'pty' +require 'timeout' +require_relative 'test' + +# Error class for when expect times out. +class ExpectTimeoutError < StandardError + def initialize(string) + super("Timeout while expecting string: #{string}") + end +end + +# Provide boilderplate for expecting a string and throwing an error on failure. +class SubtestBase + TIMEOUT_SECONDS = 3 + + def expect_or_raise(io, string, timeout = TIMEOUT_SECONDS) + raise ExpectTimeoutError, string if io.expect(string, timeout).nil? + end +end + +# Monkey-patch IO so that we get access to the buffer of a previously unsuccessful expect(). +class IO + def unused_buf + @unusedBuf + end +end + +# A wrapper class that records characters that have been received from a PTY. +class PTYLoggerWrapper + def initialize(pty, linebreak = "\n") + @pty = pty + @linebreak = linebreak + @log = [] + end + + def expect(pattern, timeout) + result = @pty.expect(pattern, timeout) + @log << if result.nil? + @pty.unused_buf + else + result + end + + result + end + + def log + @log.join.split(@linebreak) + end +end + +# A test doing console I/O with the QEMU binary. +class ConsoleIOTest < Test + MAX_TIME_ALL_TESTS_SECONDS = 20 + + def initialize(qemu_cmd, test_name, console_subtests) + super() + + @qemu_cmd = qemu_cmd + @console_subtests = console_subtests + + @test_name = test_name + @test_description = "Running #{@console_subtests.length} console I/O tests" + @test_output = [] + @test_error = nil + end + + private + + def format_test_name(number, name) + formatted_name = "#{number.to_s.rjust(3)}. #{name}" + formatted_name.ljust(63, '.') + end + + def run_subtest(subtest, test_id, qemu_out, qemu_in) + @test_output << format_test_name(test_id, subtest.name) + subtest.run(qemu_out, qemu_in) + @test_output.last.concat('[ok]') + end + + # override + def setup + qemu_out, @qemu_in = PTY.spawn(@qemu_cmd) + @qemu_out_wrapped = PTYLoggerWrapper.new(qemu_out) + end + + # override + def finish + @test_output << '' + @test_output << 'Console log:' + @test_output += @qemu_out_wrapped.log.map { |line| " #{line}" } + end + + # override + def run_concrete_test + @test_error = false + + Timeout.timeout(MAX_TIME_ALL_TESTS_SECONDS) do + @console_subtests.each_with_index do |t, i| + run_subtest(t, i + 1, @qemu_out_wrapped, @qemu_in) + end + end + rescue Errno::EIO => e + @test_error = "#{e.inspect} - QEMU might have quit early" + rescue Timeout::Error + @test_error = "Overall time for tests exceeded (#{MAX_TIME_ALL_TESTS_SECONDS}s)" + rescue StandardError => e + @test_error = e.inspect + end +end diff --git a/common/tests/dispatch.rb b/common/tests/dispatch.rb new file mode 100755 index 000000000..967937107 --- /dev/null +++ b/common/tests/dispatch.rb @@ -0,0 +1,41 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +file_dir = File.dirname(__FILE__) +$LOAD_PATH.unshift(file_dir) unless $LOAD_PATH.include?(file_dir) + +require 'boot_test' +require 'console_io_test' +require 'exit_code_test' + +qemu_cmd = ARGV.join(' ') +binary = ARGV.last +test_name = binary.gsub(%r{.*deps/}, '').split('-')[0] + +# Check if virtual manifest (tutorial 12 or later) or not +path_prefix = File.exist?('kernel/Cargo.toml') ? 'kernel/' : '' + +case test_name +when 'kernel8.img' + load "#{path_prefix}tests/boot_test_string.rb" # provides 'EXPECTED_PRINT' + BootTest.new(qemu_cmd, EXPECTED_PRINT).run # Doesn't return + +when 'libkernel' + ExitCodeTest.new(qemu_cmd, 'Kernel library unit tests').run # Doesn't return + +else + console_test_file = "#{path_prefix}tests/#{test_name}.rb" + test_name.concat('.rs') + test = if File.exist?(console_test_file) + load console_test_file # provides 'subtest_collection' + ConsoleIOTest.new(qemu_cmd, test_name, subtest_collection) + else + ExitCodeTest.new(qemu_cmd, test_name) + end + + test.run # Doesn't return +end diff --git a/common/tests/exit_code_test.rb b/common/tests/exit_code_test.rb new file mode 100644 index 000000000..900510d41 --- /dev/null +++ b/common/tests/exit_code_test.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +require 'English' +require_relative 'test' +require 'io/wait' + +# A test that only inspects the exit code of the QEMU binary. +class ExitCodeTest < Test + MAX_WAIT_SECS = 5 + + def initialize(qemu_cmd, test_name) + super() + + @qemu_cmd = qemu_cmd + + @test_name = test_name + @test_description = nil + @test_output = [] + @test_error = nil + end + + private + + # override + def setup + @qemu_serial = IO.popen(@qemu_cmd) + end + + # override + # Convert the recorded output to an array of lines, and extract the test description. + def finish + @test_output = @test_output.join.split("\n") + @test_description = @test_output.shift + end + + # override + def run_concrete_test + Timeout.timeout(MAX_WAIT_SECS) do + @test_output << @qemu_serial.read_nonblock(1024) while @qemu_serial.wait_readable + end + rescue EOFError + @qemu_serial.close + @test_error = $CHILD_STATUS.to_i.zero? ? false : 'QEMU exit status != 0' + rescue Timeout::Error + @test_error = 'Timed out waiting for test' + rescue StandardError => e + @test_error = e.inspect + end +end diff --git a/common/tests/test.rb b/common/tests/test.rb new file mode 100644 index 000000000..65afad0b2 --- /dev/null +++ b/common/tests/test.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2019-2023 Andre Richter + +# Test base class. +class Test + INDENT = ' ' + + def initialize + # Template instance variables. + # @test_name + # @test_description + # @test_output + # @test_error + end + + private + + def print_border(content) + puts "#{INDENT}-------------------------------------------------------------------" + puts content + puts "#{INDENT}-------------------------------------------------------------------" + end + + def print_header + print_border("#{INDENT}🦀 #{@test_description}") + puts + end + + def print_footer_error(error) + puts + print_border("#{INDENT}❌ Failure: #{@test_name}: #{error}") + puts + puts + end + + def print_footer_success + puts + print_border("#{INDENT}✅ Success: #{@test_name}") + puts + puts + end + + # Expects @test_output the be an array of lines, without '\n' + def print_output + @test_output.each { |x| print "#{INDENT}#{x}\n" } + end + + # Template method. + def setup; end + + # Template method. + def finish; end + + # Template method. + def run_concrete_test + raise('Not implemented') + end + + public + + def run + setup + run_concrete_test + finish + + print_header + print_output + + exit_code = if @test_error + print_footer_error(@test_error) + false + else + print_footer_success + true + end + + exit(exit_code) + end +end diff --git a/contributor_setup.sh b/contributor_setup.sh index d379dba7d..26a4059e4 100755 --- a/contributor_setup.sh +++ b/contributor_setup.sh @@ -2,7 +2,35 @@ git config core.hooksPath .githooks -bundle config set path '.vendor/bundle' +# +# Ruby and Bundler +# +if ! command -v bundle &> /dev/null +then + echo "'bundle' could not be found. Please install Ruby and Bundler." + exit +fi +bundle config set --local path '.vendor/bundle' bundle install +# +# NPM +# +if ! command -v npm &> /dev/null +then + echo "'npm' could not be found. Please install it." + exit +fi npm install --save-dev --save-exact prettier + +# +# Misspell +# +if ! command -v curl &> /dev/null +then + echo "'curl' could not be found. Please install it." + exit +fi +curl -L -o ./install-misspell.sh https://raw.githubusercontent.com/client9/misspell/master/install-misspell.sh +sh ./install-misspell.sh -b .vendor +rm install-misspell.sh diff --git a/devtool_completion.bash b/devtool_completion.bash index e351aa2ee..ce4c67b00 100755 --- a/devtool_completion.bash +++ b/devtool_completion.bash @@ -1,3 +1,3 @@ #!/usr/bin/env bash -complete -W "clean clippy copyright diff fmt fmt_check make make_xtra misspell ready_for_publish ready_for_publish_no_rust rubocop test_integration test_unit update" devtool +complete -W "clean clippy copyright diff fmt fmt_check make make_xtra misspell ready_for_publish ready_for_publish_no_rust rubocop test test_boot test_integration test_unit test_xtra update" devtool diff --git a/doc/12_demo.gif b/doc/12_demo.gif new file mode 100644 index 000000000..8afa23c12 Binary files /dev/null and b/doc/12_demo.gif differ diff --git a/doc/13_demo.gif b/doc/13_demo.gif deleted file mode 100644 index 959e35abc..000000000 Binary files a/doc/13_demo.gif and /dev/null differ diff --git a/doc/18_stack_frames.png b/doc/18_stack_frames.png new file mode 100644 index 000000000..781732f6c Binary files /dev/null and b/doc/18_stack_frames.png differ diff --git a/doc/demo_PS1.txt b/doc/demo_PS1.txt new file mode 100644 index 000000000..f83e206e0 --- /dev/null +++ b/doc/demo_PS1.txt @@ -0,0 +1 @@ +export PS1="\[\033[01;32m\]rust@osdev\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\] >> " diff --git a/doc/wiring.fzz b/doc/wiring.fzz new file mode 100644 index 000000000..55f80ec8d Binary files /dev/null and b/doc/wiring.fzz differ diff --git a/doc/wiring.png b/doc/wiring.png index bf2d08408..d79dfb9d2 100644 Binary files a/doc/wiring.png and b/doc/wiring.png differ diff --git a/docker/rustembedded-osdev-utils/Dockerfile b/docker/rustembedded-osdev-utils/Dockerfile index 0ee3d9886..e8cb2cb52 100644 --- a/docker/rustembedded-osdev-utils/Dockerfile +++ b/docker/rustembedded-osdev-utils/Dockerfile @@ -1,10 +1,12 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2017-2020 Andre Richter -## Copyright (c) 2019-2020 Nao Taco +## Copyright (c) 2017-2023 Andre Richter +## Copyright (c) 2019-2023 Nao Taco FROM ubuntu:20.04 ARG VCS_REF +ARG GCC_AARCH64=https://developer.arm.com/-/media/Files/downloads/gnu-a/10.3-2021.07/binrel/gcc-arm-10.3-2021.07-aarch64-aarch64-none-elf.tar.xz +ARG GCC_X86_64=https://developer.arm.com/-/media/Files/downloads/gnu-a/10.3-2021.07/binrel/gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz LABEL org.label-schema.vcs-ref=$VCS_REF \ org.label-schema.vcs-url="https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials" @@ -14,42 +16,53 @@ LABEL maintainer="The resources team , Andre # Ruby gems COPY Gemfile . -RUN set -ex; \ - tempPkgs=' \ - automake \ - bison \ - build-essential \ - flex \ - git \ - libtool \ - pkg-config \ - wget \ - '; \ - apt-get update; \ - apt-get install -q -y --no-install-recommends \ - $tempPkgs \ +RUN set -ex; \ + tempPkgs=' \ + automake \ + bison \ + build-essential \ + flex \ + git \ + libtool \ + ninja-build \ + pkg-config \ + wget \ + '; \ + apt-get update; \ + apt-get install -q -y --no-install-recommends \ + $tempPkgs \ # persistent packages - ca-certificates \ - gdb-multiarch \ - libpixman-1-dev \ - libglib2.0-dev \ - libusb-1.0.0-dev \ - locales \ - python3 \ - ruby \ - ruby-dev \ - ; \ + ca-certificates \ + gdb-multiarch \ + libpixman-1-dev \ + libglib2.0-dev \ + libusb-1.0.0-dev \ + locales \ + python3 \ + ruby \ + ruby-dev \ + ; \ + # GCC AArch64 tools + if [ "$(uname -m)" = "aarch64" ]; then wget ${GCC_AARCH64}; else wget ${GCC_X86_64}; fi; \ + tar -xf gcc-arm-10*; \ + cp \ + gcc-arm-10*/bin/aarch64-none-elf-objdump \ + gcc-arm-10*/bin/aarch64-none-elf-readelf \ + gcc-arm-10*/bin/aarch64-none-elf-nm \ + /usr/local/bin/; \ + rm -rf gcc-arm-10*; \ # Ruby dependencies - gem install bundler; \ - bundle install --retry 3 --without development; \ + gem install bundler; \ + bundle config set --local without 'development'; \ + bundle install --retry 3; \ # QEMU - git clone git://git.qemu.org/qemu.git; \ + git clone https://gitlab.com/qemu-project/qemu.git; \ cd qemu; \ - git checkout tags/v5.1.0; \ + git checkout tags/v6.1.0; \ ./configure --target-list=aarch64-softmmu --enable-modules \ --enable-tcg-interpreter --enable-debug-tcg \ --python=/usr/bin/python3; \ - make -j8; \ + make -j10; \ make install; \ cd ..; \ rm -rf qemu; \ @@ -58,26 +71,21 @@ RUN set -ex; \ cd openocd; \ ./bootstrap; \ ./configure --enable-ftdi; \ - make -j8; \ + make -j10; \ make install; \ # GDB - wget -P ~ git.io/.gdbinit; \ - # GCC AArch64 tools - wget https://developer.arm.com/-/media/Files/downloads/gnu-a/9.2-2019.12/binrel/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf.tar.xz; \ - tar -xf gcc-arm-9*; \ - cp gcc-arm-9*/bin/aarch64-none-elf-objdump gcc-arm-9*/bin/aarch64-none-elf-nm /usr/local/bin/; \ - rm -rf gcc-arm-9*; \ + wget -P ~ git.io/.gdbinit; \ # Cleanup - apt-get purge -y --auto-remove $tempPkgs; \ - apt-get autoremove -q -y; \ - apt-get clean -q -y; \ + apt-get purge -y --auto-remove $tempPkgs; \ + apt-get autoremove -q -y; \ + apt-get clean -q -y; \ rm -rf /var/lib/apt/lists/* # Locales RUN locale-gen en_US.UTF-8 -ENV LANG=en_US.UTF-8 \ - LANGUAGE=en_US:en \ +ENV LANG=en_US.UTF-8 \ + LANGUAGE=en_US:en \ LC_ALL=en_US.UTF-8 \ RUBYOPT=-W0 diff --git a/docker/rustembedded-osdev-utils/Makefile b/docker/rustembedded-osdev-utils/Makefile index 4b9f70f5e..57acd9956 100644 --- a/docker/rustembedded-osdev-utils/Makefile +++ b/docker/rustembedded-osdev-utils/Makefile @@ -1,11 +1,25 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2019-2020 Andre Richter +## Copyright (c) 2019-2023 Andre Richter -default: docker_build +# Reference followed: https://www.docker.com/blog/getting-started-with-docker-for-arm-on-linux -docker_build: +TAG := 2021.12 + +default: build_local + +build_local: + cp ../../Gemfile . + docker build \ + --tag rustembedded/osdev-utils:$(TAG) \ + --build-arg VCS_REF=`git rev-parse --short HEAD` . + rm Gemfile + +buildx_push: cp ../../Gemfile . - docker build -t rustembedded/osdev-utils \ - --build-arg VCS_REF=`git rev-parse --short HEAD` . + docker buildx build \ + --push \ + --platform linux/arm64/v8,linux/amd64 \ + --tag rustembedded/osdev-utils:$(TAG) \ + --build-arg VCS_REF=`git rev-parse --short HEAD` . rm Gemfile diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 000000000..a554c0a98 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "nightly-2022-10-13" +components = ["rust-src", "llvm-tools-preview", "rustfmt"] +targets = ["aarch64-unknown-none-softfloat"] diff --git a/utils/devtool.rb b/utils/devtool.rb index d104f31c6..2b120d6bc 100755 --- a/utils/devtool.rb +++ b/utils/devtool.rb @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2020 Andre Richter +# Copyright (c) 2020-2023 Andre Richter require 'rubygems' require 'bundler/setup' @@ -11,7 +11,7 @@ require 'fileutils' require_relative 'devtool/copyright' -# Actions for tutorial folders +# Actions for tutorial folders. class TutorialCrate attr_reader :folder @@ -26,70 +26,89 @@ def tutorial? def clean puts 'Cleaning '.light_blue + @folder - Dir.chdir(@folder) { system('make clean') } + # No output needed. + Dir.chdir(@folder) { `make clean` } end def update + puts "\n\n" puts 'Updating '.light_blue + @folder Dir.chdir(@folder) { system('cargo update') } end def clippy(bsp) + puts "\n\n" puts "Clippy #{@folder} - BSP: #{bsp}".light_blue Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make clippy") } end def fmt_cargo_rust(args) - print 'Rust cargo fmt '.light_blue - print "#{args} ".light_blue unless args.nil? - puts @folder - Dir.chdir(@folder) { exit(1) unless system("cargo fmt #{args}") } end def make(bsp) + puts "\n\n" puts "Make #{@folder} - BSP: #{bsp}".light_blue Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make") } end - def test_unit - return unless testable? + def test(bsp) + return unless boot_test? - puts "Unit Tests #{@folder}".light_blue + puts "\n\n" + puts "Test #{@folder} - BSP: #{bsp}".light_blue - Dir.chdir(@folder) { exit(1) unless system('TEST=unit make test') } + Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make test") } end - def test_integration - return unless testable? + def test_boot(bsp) + return unless boot_test? - puts "Integration Tests #{@folder}".light_blue + puts "\n\n" + puts "Test Boot #{@folder} - BSP: #{bsp}".light_blue - Dir.chdir(@folder) do - Dir['tests/*.rs'].sort.each do |t| - t = t.delete_prefix('tests/').delete_suffix('.rs') - exit(1) unless system("TEST=#{t} make test") - end - end + Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make test_boot") } + end + + def test_unit(bsp) + return unless unit_integration_tests? + + puts "\n\n" + puts "Test Unit #{@folder} - BSP: #{bsp}".light_blue + + Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make test_unit") } + end + + def test_integration(bsp) + return unless unit_integration_tests? + + puts "\n\n" + puts "Test Integration #{@folder} - BSP: #{bsp}".light_blue + + Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make test_integration") } end private - def testable? - Dir.exist?("#{@folder}/tests") + def boot_test? + Dir.exist?("#{@folder}/tests") || Dir.exist?("#{@folder}/kernel/tests") + end + + def unit_integration_tests? + !Dir.glob("#{@folder}/kernel/tests/00_*.rs").empty? end end -# Forks commands to all applicable receivers +# Forks commands to all applicable receivers. class DevTool def initialize @user_has_supplied_crates = false @bsp = bsp_from_env || SUPPORTED_BSPS.first - cl = user_supplied_crate_list || Dir['*/Cargo.toml'].sort + cl = user_supplied_crate_list || Dir['*/Cargo.toml'] @crates = cl.map { |c| TutorialCrate.new(c.delete_suffix('/Cargo.toml')) } end @@ -104,11 +123,7 @@ def update def clippy(bsp = nil) bsp ||= @bsp - @crates.each do |c| - c.clippy(bsp) - puts - puts - end + @crates.each { |c| c.clippy(bsp) } end def diff @@ -136,26 +151,40 @@ def fmt_check def make(bsp = nil) bsp ||= @bsp - @crates.each do |c| - c.make(bsp) - puts - puts - end + @crates.each { |c| c.make(bsp) } end def make_xtra return if @user_has_supplied_crates - puts 'Make Xtra crates'.light_blue + puts "\n\n" + puts 'Make Xtra stuff'.light_blue + system('cd *_uart_chainloader && bash update.sh') system('cd X1_JTAG_boot && bash update.sh') end - def test_unit - @crates.each(&:test_unit) + def test(bsp = nil) + bsp ||= @bsp + + @crates.each { |c| c.test(bsp) } + end + + def test_boot(bsp = nil) + bsp ||= @bsp + + @crates.each { |c| c.test_boot(bsp) } end - def test_integration - @crates.each(&:test_integration) + def test_unit(bsp = nil) + bsp ||= @bsp + + @crates.each { |c| c.test_unit(bsp) } + end + + def test_integration(bsp = nil) + bsp ||= @bsp + + @crates.each { |c| c.test_integration(bsp) } end def copyright @@ -164,7 +193,12 @@ def copyright def misspell puts 'Misspell'.light_blue - exit(1) unless system("~/bin/misspell -error #{tracked_files.join(' ')}") + + translations = ['README.CN.md', 'README.ES.md'] + files = tracked_files.reject { |f| translations.include?(File.basename(f)) } + files = files.join(' ') + + exit(1) unless system(".vendor/misspell -error #{files}") end def rubocop @@ -172,31 +206,25 @@ def rubocop exit(1) unless system('bundle exec rubocop') end - def ready_for_publish + def ready_for_publish_no_rust clean fmt - misspell rubocop - clippy('rpi4') - clippy('rpi3') copyright diff - - clean - make('rpi4') - make('rpi3') - make_xtra - test_unit - test_integration + misspell clean end - def ready_for_publish_no_rust - clean - misspell - rubocop - copyright - diff + def ready_for_publish + ready_for_publish_no_rust + + make_xtra + clippy('rpi4') + clippy('rpi3') + test_boot('rpi3') + test_unit('rpi3') + test_integration('rpi3') clean end @@ -205,7 +233,7 @@ def ready_for_publish_no_rust SUPPORTED_BSPS = %w[rpi3 rpi4].freeze def bsp_from_env - bsp = ENV['BSP'] + bsp = ENV.fetch('BSP', nil) return bsp if SUPPORTED_BSPS.include?(bsp) @@ -215,7 +243,14 @@ def bsp_from_env def fmt_cargo_rust(check: false) args = '-- --check' if check - @crates.each { |c| c.fmt_cargo_rust(args) } + @crates.each do |c| + print 'Rust cargo fmt '.light_blue + print "#{args} ".light_blue unless args.nil? + puts c.folder + + Process.fork { c.fmt_cargo_rust(args) } + end + Process.waitall end def fmt_prettier(check: false) @@ -266,7 +301,15 @@ def diff_pair(original, update, padding) # Only diff adjacent tutorials. This checks the numbers of the tutorial folders. return unless original[0..1].to_i + 1 == update[0..1].to_i - puts 'Diffing '.light_blue + original.ljust(padding) + " -> #{update}" + # Skip for tutorial 11. Due to the change to virtual manifest, the diff is rather + # unreadable. + if original[0..1].to_i == 11 + puts 'Skipping '.light_yellow + + "#{original}: Too noisy due to change to virtual manifest" + return + end + + puts 'Diffing '.light_blue + original.ljust(padding) + " -> #{update}" system("bash utils/diff_tut_folders.bash #{original} #{update}") end @@ -277,6 +320,7 @@ def copyright_source_files tracked_files.select do |f| next unless File.exist?(f) next if f.include?('build.rs') + next if f.include?('boot_test_string.rb') f.include?('Makefile') || f.include?('Dockerfile') || @@ -285,9 +329,9 @@ def copyright_source_files end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Execution starts here -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- tool = DevTool.new cmd = ARGV[0] commands = tool.public_methods(false).sort @@ -299,4 +343,5 @@ def copyright_source_files puts puts 'Commands:' commands.each { |m| puts " #{m}" } + exit(1) end diff --git a/utils/devtool/copyright.rb b/utils/devtool/copyright.rb index 5da012562..d1aed8512 100644 --- a/utils/devtool/copyright.rb +++ b/utils/devtool/copyright.rb @@ -2,8 +2,10 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2018-2020 Andre Richter +# Copyright (c) 2018-2023 Andre Richter +require 'rubygems' +require 'bundler/setup' require 'colorize' def copyright_check_files(source_files) diff --git a/utils/diff_tut_folders.bash b/utils/diff_tut_folders.bash index 6952f8e8b..cdd9880e1 100755 --- a/utils/diff_tut_folders.bash +++ b/utils/diff_tut_folders.bash @@ -2,21 +2,21 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2018-2020 Andre Richter +# Copyright (c) 2018-2023 Andre Richter DIFF=$( diff -uNr \ -x README.md \ -x README.CN.md \ - -x kernel \ + -x README.ES.md \ -x kernel8.img \ -x Cargo.lock \ -x target \ $1 $2 \ - | sed -r "s/[12][90][127][90]-[0-9][0-9]-[0-9][0-9] .*//g" \ + | sed -r "s/[12][90][127][0-9]-[0-9][0-9]-[0-9][0-9] .*//g" \ | sed -r "s/[[:space:]]*$//g" \ | sed -r "s/%/modulo/g" \ - | sed -r "s/diff -uNr -x README.md -x README.CN.md -x kernel -x kernel8.img -x Cargo.lock -x target/\ndiff -uNr/g" + | sed -r "s/diff -uNr -x README.md -x README.CN.md -x README.ES.md -x kernel8.img -x Cargo.lock -x target/\ndiff -uNr/g" ) HEADER="## Diff to previous" diff --git a/utils/minipush.rb b/utils/minipush.rb deleted file mode 100755 index 9c743bd32..000000000 --- a/utils/minipush.rb +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2020 Andre Richter - -require_relative 'miniterm' -require 'ruby-progressbar' -require_relative 'minipush/progressbar_patch' -require 'timeout' - -class ProtocolError < StandardError; end - -# The main class -class MiniPush < MiniTerm - def initialize(serial_name, binary_image_path) - super(serial_name) - - @name_short = 'MP' - @binary_image_path = binary_image_path - @binary_size = nil - @binary_image = nil - end - - private - - # The three characters signaling the request token are expected to arrive as the last three - # characters _at the end_ of a character stream (e.g. after a header print from Miniload). - def wait_for_binary_request - Timeout.timeout(7) do - loop do - received = @target_serial.readpartial(4096) - - raise ConnectionError if received.nil? - - if received.chars.last(3) == ["\u{3}", "\u{3}", "\u{3}"] - # Print the last chunk minus the request token. - print received[0..-4] - return - end - - print received - end - end - end - - def load_binary - @binary_size = File.size(@binary_image_path) - @binary_image = File.binread(@binary_image_path) - end - - def send_size - @target_serial.print([@binary_size].pack('L<')) - raise ProtocolError if @target_serial.read(2) != 'OK' - end - - def send_binary - pb = ProgressBar.create( - total: @binary_size, - format: "[#{@name_short}] ⏩ Pushing %k KiB %b🦀%i %p%% %r KiB/s %a", - rate_scale: ->(rate) { rate / 1024 }, - length: 92 - ) - - # Send in 512 byte chunks. - while pb.progress < pb.total - part = @binary_image.slice(pb.progress, 512) - pb.progress += @target_serial.write(part) - end - end - - # When the serial is still powered. - def handle_protocol_error - connetion_reset - - puts - puts "[#{@name_short}] ⚡ " \ - "#{'Protocol Error: Remove and insert the USB serial again'.light_red}" - sleep(1) while serial_connected? - end - - public - - def run - open_serial - wait_for_binary_request - load_binary - send_size - send_binary - terminal - rescue ConnectionError, EOFError, Errno::EIO - handle_reconnect - retry - rescue ProtocolError, Timeout::Error - handle_protocol_error - retry - rescue StandardError => e - handle_unexpected(e) - ensure - connetion_reset - puts - puts "[#{@name_short}] Bye 👋" - end -end - -puts 'Minipush 1.0'.cyan -puts - -# CTRL + C handler. Only here to suppress Ruby's default exception print. -trap('INT') do - # The `ensure` block from `MiniPush::run` will run after exit, restoring console state. - exit -end - -MiniPush.new(ARGV[0], ARGV[1]).run diff --git a/utils/update_copyright.rb b/utils/update_copyright.rb new file mode 100755 index 000000000..dc1abbf42 --- /dev/null +++ b/utils/update_copyright.rb @@ -0,0 +1,17 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require 'date' + +files = `git ls-files`.split("\n") +files = files.delete_if { |f| File.symlink?(f) } +files = files.join(' ') + +year = Date.today.year + +`sed -i -- 's,\\(Copyright .* 20..\\)-20..,\\1-#{year},g' #{files}` +`sed -i -- 's,\\(Copyright .* #{year - 1}\\) ,\\1-#{year} ,g' #{files}`