diff --git a/.editorconfig b/.editorconfig index dd8892ca..4d2b34c1 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 diff --git a/.githooks/pre-commit b/.githooks/pre-commit index e9570651..71381892 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2018-2022 Andre Richter +# Copyright (c) 2018-2023 Andre Richter require_relative '../utils/devtool/copyright' @@ -23,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 index 98339970..f6167fff 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -10,4 +10,5 @@ Related Issue: - 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 d6dcfa3f..b3b997b3 100644 --- a/.github/workflows/build_rpi3.yml +++ b/.github/workflows/build_rpi3.yml @@ -1,40 +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: 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: 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 de47cc83..ca15786e 100644 --- a/.github/workflows/build_rpi4.yml +++ b/.github/workflows/build_rpi4.yml @@ -1,40 +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: 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: 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 4f058992..3eb0f088 100644 --- a/.github/workflows/sanity.yml +++ b/.github/workflows/sanity.yml @@ -1,46 +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: 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://git.io/misspell - 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 + 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 8c18c0a0..7e3ab076 100644 --- a/.github/workflows/test_integration.yml +++ b/.github/workflows/test_integration.yml @@ -1,40 +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: 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: 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 624cf16d..9ac56432 100644 --- a/.github/workflows/test_unit.yml +++ b/.github/workflows/test_unit.yml @@ -1,40 +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: 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: 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 index 97fa2081..cdc705f9 100644 --- a/.github/workflows/test_xtra.yml +++ b/.github/workflows/test_xtra.yml @@ -1,40 +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 * * *" + 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-20.04 + build: + name: Run xtra tests + runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v2 - - name: Set up Ruby 2.x - 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: Make all - run: | - bundle exec ruby utils/devtool.rb test_xtra + 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 19660052..5bc8cd8d 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 0967ef42..864ccc36 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 b0f756ac..059ba16e 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -10,23 +10,23 @@ # See https://github.com/rubocop-hq/rubocop/blob/master/manual/configuration.md Layout/IndentationWidth: - Width: 4 - IgnoredPatterns: ['^\s*module'] + Width: 4 + AllowedPatterns: ['^\s*module'] Layout/LineLength: - Max: 100 + Max: 100 Lint/UnusedMethodArgument: - AutoCorrect: False + AutoCorrect: False Metrics/AbcSize: - Max: 25 + 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 index 1effb003..b5021469 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -2.7 +3.0.2 diff --git a/.rustfmt.toml b/.rustfmt.toml index 33aca681..c05f1817 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -5,5 +5,3 @@ 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 d77cd337..9ef30cd0 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/01_wait_forever/.vscode/settings.json b/01_wait_forever/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/01_wait_forever/.vscode/settings.json +++ b/01_wait_forever/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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.toml b/01_wait_forever/Cargo.toml index 459866f8..c2815c32 100644 --- a/01_wait_forever/Cargo.toml +++ b/01_wait_forever/Cargo.toml @@ -20,4 +20,4 @@ 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 cd987db5..51c128f7 100644 --- a/01_wait_forever/Makefile +++ b/01_wait_forever/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -51,14 +52,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -81,7 +82,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -131,7 +131,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -190,8 +190,3 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target 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 281a9290..06b2178d 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 index 5244372a..0d86a4ea 100644 --- a/01_wait_forever/README.ES.md +++ b/01_wait_forever/README.ES.md @@ -9,37 +9,37 @@ ## 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. - + + * `objdump`: Inspecciona el ensamblador. + * `nm`: Inspecciona los símbolos. ## Código a revisar -* El script para enlazado específico para la `BSP` llamado `link.ld`. - +* 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()`. +* `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 diff --git a/01_wait_forever/README.md b/01_wait_forever/README.md index 9c6eaf76..73b15af5 100644 --- a/01_wait_forever/README.md +++ b/01_wait_forever/README.md @@ -18,7 +18,7 @@ ## Code to look at -- `BSP`-specific `link.ld` linker script. +- `BSP`-specific `kernel.ld` linker script. - Load address at `0x8_0000` - Only `.text` section. - `main.rs`: Important [inner attributes]: diff --git a/01_wait_forever/src/_arch/aarch64/cpu/boot.rs b/01_wait_forever/src/_arch/aarch64/cpu/boot.rs index b5cc68fc..3cf9b08f 100644 --- a/01_wait_forever/src/_arch/aarch64/cpu/boot.rs +++ b/01_wait_forever/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,5 +11,7 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +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 index d5b5bc9c..8f33b483 100644 --- a/01_wait_forever/src/_arch/aarch64/cpu/boot.s +++ b/01_wait_forever/src/_arch/aarch64/cpu/boot.s @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/01_wait_forever/src/bsp.rs b/01_wait_forever/src/bsp.rs index a09ba8a4..b128add9 100644 --- a/01_wait_forever/src/bsp.rs +++ b/01_wait_forever/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/01_wait_forever/src/bsp/raspberrypi.rs b/01_wait_forever/src/bsp/raspberrypi.rs index 26b678a0..3253ee5e 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-2022 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/link.ld b/01_wait_forever/src/bsp/raspberrypi/kernel.ld similarity index 100% rename from 01_wait_forever/src/bsp/raspberrypi/link.ld rename to 01_wait_forever/src/bsp/raspberrypi/kernel.ld diff --git a/01_wait_forever/src/cpu.rs b/01_wait_forever/src/cpu.rs index 8f50133f..9f399de2 100644 --- a/01_wait_forever/src/cpu.rs +++ b/01_wait_forever/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/01_wait_forever/src/cpu/boot.rs b/01_wait_forever/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/01_wait_forever/src/cpu/boot.rs +++ b/01_wait_forever/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/01_wait_forever/src/main.rs b/01_wait_forever/src/main.rs index 4f405bec..10fdb3f4 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-2022 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. //! diff --git a/01_wait_forever/src/panic_wait.rs b/01_wait_forever/src/panic_wait.rs index c9a8f5e4..714bf296 100644 --- a/01_wait_forever/src/panic_wait.rs +++ b/01_wait_forever/src/panic_wait.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. diff --git a/02_runtime_init/.vscode/settings.json b/02_runtime_init/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/02_runtime_init/.vscode/settings.json +++ b/02_runtime_init/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 6e58e97a..e52e7fdf 100644 --- a/02_runtime_init/Cargo.lock +++ b/02_runtime_init/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,11 +15,11 @@ dependencies = [ name = "mingo" version = "0.2.0" dependencies = [ - "cortex-a", + "aarch64-cpu", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/02_runtime_init/Cargo.toml b/02_runtime_init/Cargo.toml index 52786a40..5946f43c 100644 --- a/02_runtime_init/Cargo.toml +++ b/02_runtime_init/Cargo.toml @@ -24,4 +24,4 @@ path = "src/main.rs" # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/02_runtime_init/Makefile b/02_runtime_init/Makefile index d1d71ec9..893564e2 100644 --- a/02_runtime_init/Makefile +++ b/02_runtime_init/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -51,14 +52,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -81,7 +82,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -131,7 +131,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -182,7 +182,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -192,8 +191,3 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target 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 51c63793..0272e057 100644 --- a/02_runtime_init/README.CN.md +++ b/02_runtime_init/README.CN.md @@ -2,319 +2,29 @@ ## tl;dr -我们拓展了`boot.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/Cargo.toml 02_runtime_init/Cargo.toml ---- 01_wait_forever/Cargo.toml -+++ 02_runtime_init/Cargo.toml -@@ -4,6 +4,9 @@ - authors = ["Andre Richter "] - edition = "2018" - -+[profile.release] -+lto = true -+ - # The features section is used to select the target board. - [features] - default = [] - -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 -@@ -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/_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,30 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2022 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 -+ -+//-------------------------------------------------------------------------------------------------- -+// 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 -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*) -+ } -+ -+ .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 -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 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2022 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 -uNr 01_wait_forever/src/bsp/raspberrypi.rs 02_runtime_init/src/bsp/raspberrypi.rs ---- 01_wait_forever/src/bsp/raspberrypi.rs -+++ 02_runtime_init/src/bsp/raspberrypi.rs -@@ -4,4 +4,4 @@ - - //! Top-level BSP file for the Raspberry Pi 3 and 4. - --// Coming soon. -+pub mod memory; - -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 -@@ -102,6 +102,7 @@ - //! - //! 1. The kernel's entry point is the function [`cpu::boot::arch_boot::_start()`]. - //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.rs`. -+//! 2. Once finished with architectural setup, the arch code calls [`runtime_init::runtime_init()`]. - //! - //! [`cpu::boot::arch_boot::_start()`]: cpu/boot/arch_boot/fn._start.html - -@@ -112,6 +113,15 @@ - - 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,30 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2022 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,9 +4,10 @@ - - //! A panic handler that infinitely waits. - -+use crate::cpu; - use core::panic::PanicInfo; - - #[panic_handler] - fn panic(_info: &PanicInfo) -> ! { -- unimplemented!() -+ cpu::wait_forever() - } - -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-2022 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/02_runtime_init/README.ES.md b/02_runtime_init/README.ES.md index 6a5b3974..2f93586f 100644 --- a/02_runtime_init/README.ES.md +++ b/02_runtime_init/README.ES.md @@ -8,341 +8,30 @@ ## Adiciones importantes -* Adiciones importantes al script `link.ld`: - +* 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 [cortex-a](https://github.com/rust-embedded/cortex-a), 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. - +* 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 -```diff -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] -+cortex-a = { version = "7.x.x" } - -diff -uNr 01_wait_forever/Makefile 02_runtime_init/Makefile ---- 01_wait_forever/Makefile -+++ 02_runtime_init/Makefile -@@ -153,6 +153,8 @@ - $(call colorecho, "\nLaunching objdump") - @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ - --section .text \ -+ --section .rodata \ -+ --section .got \ - $(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 -@@ -13,3 +13,15 @@ - - // Assembly counterpart to this file. - core::arch::global_asm!(include_str!("boot.s")); -+ -+//-------------------------------------------------------------------------------------------------- -+// 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,24 @@ - // 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 -+ -+.equ _core_id_mask, 0b11 -+ -+//-------------------------------------------------------------------------------------------------- - // Public Code - //-------------------------------------------------------------------------------------------------- - .section .text._start -@@ -11,6 +29,34 @@ - // fn _start() - //------------------------------------------------------------------------------ - _start: -+ // Only proceed on the boot core. Park it otherwise. -+ mrs x1, MPIDR_EL1 -+ and x1, x1, _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 -+ -+ // 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/_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-2022 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 cortex_a::asm; -+ -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// 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-2022 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 -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 -@@ -3,6 +3,8 @@ - * 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; - -@@ -13,21 +15,58 @@ - * 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 -+ .got : ALIGN(8) { *(.got) } :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 - } - -diff -uNr 01_wait_forever/src/bsp/raspberrypi.rs 02_runtime_init/src/bsp/raspberrypi.rs ---- 01_wait_forever/src/bsp/raspberrypi.rs -+++ 02_runtime_init/src/bsp/raspberrypi.rs -@@ -4,4 +4,4 @@ - - //! Top-level BSP file for the Raspberry Pi 3 and 4. - --// Coming soon. -+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 -@@ -102,6 +102,7 @@ - //! - //! 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()`. - - #![no_main] - #![no_std] -@@ -110,4 +111,11 @@ - mod cpu; - mod panic_wait; - --// 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/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,9 +4,10 @@ - - //! A panic handler that infinitely waits. - -+use crate::cpu; - use core::panic::PanicInfo; - - #[panic_handler] - fn panic(_info: &PanicInfo) -> ! { -- unimplemented!() -+ cpu::wait_forever() - } -``` +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 88c29239..1082f18c 100644 --- a/02_runtime_init/README.md +++ b/02_runtime_init/README.md @@ -19,12 +19,12 @@ 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 [cortex-a] crate, which provides zero-overhead abstractions and wraps +- 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 -[cortex-a]: https://github.com/rust-embedded/cortex-a +[aarch64-cpu]: https://github.com/rust-embedded/aarch64-cpu ## Diff to previous ```diff @@ -47,28 +47,31 @@ diff -uNr 01_wait_forever/Cargo.toml 02_runtime_init/Cargo.toml + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] -+cortex-a = { version = "7.x.x" } ++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,8 @@ +@@ -181,6 +181,7 @@ $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ + --section .rodata \ -+ --section .got \ $(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 -@@ -13,3 +13,15 @@ +@@ -14,4 +14,19 @@ + use core::arch::global_asm; // Assembly counterpart to this file. - core::arch::global_asm!(include_str!("boot.s")); +-global_asm!(include_str!("boot.s")); ++global_asm!( ++ include_str!("boot.s"), ++ CONST_CORE_ID_MASK = const 0b11 ++); + +//-------------------------------------------------------------------------------------------------- +// Public Code @@ -85,8 +88,8 @@ diff -uNr 01_wait_forever/src/_arch/aarch64/cpu/boot.rs 02_runtime_init/src/_arc 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,24 @@ - // Copyright (c) 2021-2022 Andre Richter +@@ -3,6 +3,22 @@ + // Copyright (c) 2021-2023 Andre Richter //-------------------------------------------------------------------------------------------------- +// Definitions @@ -104,21 +107,19 @@ diff -uNr 01_wait_forever/src/_arch/aarch64/cpu/boot.s 02_runtime_init/src/_arch + add \register, \register, #:lo12:\symbol +.endm + -+.equ _core_id_mask, 0b11 -+ +//-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start -@@ -11,6 +29,34 @@ +@@ -11,6 +27,34 @@ // fn _start() //------------------------------------------------------------------------------ _start: + // Only proceed on the boot core. Park it otherwise. -+ mrs x1, MPIDR_EL1 -+ and x1, x1, _core_id_mask -+ ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs -+ cmp x1, x2 ++ 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. @@ -152,7 +153,7 @@ diff -uNr 01_wait_forever/src/_arch/aarch64/cpu.rs 02_runtime_init/src/_arch/aar @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Architectural processor code. +//! @@ -163,7 +164,7 @@ diff -uNr 01_wait_forever/src/_arch/aarch64/cpu.rs 02_runtime_init/src/_arch/aar +//! +//! crate::cpu::arch_cpu + -+use cortex_a::asm; ++use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code @@ -183,7 +184,7 @@ diff -uNr 01_wait_forever/src/bsp/raspberrypi/cpu.rs 02_runtime_init/src/bsp/ras @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + @@ -196,11 +197,11 @@ diff -uNr 01_wait_forever/src/bsp/raspberrypi/cpu.rs 02_runtime_init/src/bsp/ras +#[link_section = ".text._start_arguments"] +pub static BOOT_CORE_ID: u64 = 0; -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 +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-2022 Andre Richter + * Copyright (c) 2018-2023 Andre Richter */ +__rpi_phys_dram_start_addr = 0; @@ -208,7 +209,7 @@ diff -uNr 01_wait_forever/src/bsp/raspberrypi/link.ld 02_runtime_init/src/bsp/ra /* 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,58 @@ +@@ -13,21 +15,65 @@ * 4 == R * 5 == RX * 6 == RW @@ -254,7 +255,6 @@ diff -uNr 01_wait_forever/src/bsp/raspberrypi/link.ld 02_runtime_init/src/bsp/ra } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code -+ .got : ALIGN(8) { *(.got) } :segment_code + + /*********************************************************************************************** + * Data + BSS @@ -269,6 +269,14 @@ diff -uNr 01_wait_forever/src/bsp/raspberrypi/link.ld 02_runtime_init/src/bsp/ra + . = 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 @@ -302,15 +310,17 @@ diff -uNr 01_wait_forever/src/cpu.rs 02_runtime_init/src/cpu.rs 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 -@@ -102,6 +102,7 @@ +@@ -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] -@@ -110,4 +111,11 @@ + +@@ -112,4 +114,11 @@ mod cpu; mod panic_wait; diff --git a/02_runtime_init/src/_arch/aarch64/cpu.rs b/02_runtime_init/src/_arch/aarch64/cpu.rs index 3b52e3a3..11d5024e 100644 --- a/02_runtime_init/src/_arch/aarch64/cpu.rs +++ b/02_runtime_init/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/02_runtime_init/src/_arch/aarch64/cpu/boot.rs b/02_runtime_init/src/_arch/aarch64/cpu/boot.rs index 2f9654c7..2a6c4649 100644 --- a/02_runtime_init/src/_arch/aarch64/cpu/boot.rs +++ b/02_runtime_init/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,8 +11,13 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/02_runtime_init/src/_arch/aarch64/cpu/boot.s b/02_runtime_init/src/_arch/aarch64/cpu/boot.s index 7d445a93..0011c607 100644 --- a/02_runtime_init/src/_arch/aarch64/cpu/boot.s +++ b/02_runtime_init/src/_arch/aarch64/cpu/boot.s @@ -18,8 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -30,10 +28,10 @@ //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. - mrs x1, MPIDR_EL1 - and x1, x1, _core_id_mask - ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs - cmp x1, x2 + 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. diff --git a/02_runtime_init/src/bsp.rs b/02_runtime_init/src/bsp.rs index a09ba8a4..b128add9 100644 --- a/02_runtime_init/src/bsp.rs +++ b/02_runtime_init/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/02_runtime_init/src/bsp/raspberrypi.rs b/02_runtime_init/src/bsp/raspberrypi.rs index 5ab6cb34..c3abe0a6 100644 --- a/02_runtime_init/src/bsp/raspberrypi.rs +++ b/02_runtime_init/src/bsp/raspberrypi.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. diff --git a/02_runtime_init/src/bsp/raspberrypi/cpu.rs b/02_runtime_init/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/02_runtime_init/src/bsp/raspberrypi/cpu.rs +++ b/02_runtime_init/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld b/02_runtime_init/src/bsp/raspberrypi/kernel.ld similarity index 88% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld rename to 02_runtime_init/src/bsp/raspberrypi/kernel.ld index 2ce4b44b..f6c18843 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld +++ b/02_runtime_init/src/bsp/raspberrypi/kernel.ld @@ -3,9 +3,6 @@ * 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 */ @@ -45,12 +42,9 @@ SECTIONS __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)) @@ -60,10 +54,6 @@ SECTIONS } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code - - . = ALIGN(PAGE_SIZE); - __code_end_exclusive = .; /*********************************************************************************************** * Data + BSS @@ -78,4 +68,12 @@ SECTIONS . = 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 007afd4a..00000000 --- a/02_runtime_init/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,72 +0,0 @@ -/* 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 - .got : ALIGN(8) { *(.got) } :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 -} diff --git a/02_runtime_init/src/cpu.rs b/02_runtime_init/src/cpu.rs index b2a96010..13b89581 100644 --- a/02_runtime_init/src/cpu.rs +++ b/02_runtime_init/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/02_runtime_init/src/cpu/boot.rs b/02_runtime_init/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/02_runtime_init/src/cpu/boot.rs +++ b/02_runtime_init/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/02_runtime_init/src/main.rs b/02_runtime_init/src/main.rs index 398c4a04..152d7544 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-2022 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. //! @@ -104,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()`. +#![feature(asm_const)] #![no_main] #![no_std] diff --git a/02_runtime_init/src/panic_wait.rs b/02_runtime_init/src/panic_wait.rs index 7e9adfce..34a98173 100644 --- a/02_runtime_init/src/panic_wait.rs +++ b/02_runtime_init/src/panic_wait.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. diff --git a/03_hacky_hello_world/.vscode/settings.json b/03_hacky_hello_world/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/03_hacky_hello_world/.vscode/settings.json +++ b/03_hacky_hello_world/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 9b44f7de..6e5873df 100644 --- a/03_hacky_hello_world/Cargo.lock +++ b/03_hacky_hello_world/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,11 +15,11 @@ dependencies = [ name = "mingo" version = "0.3.0" dependencies = [ - "cortex-a", + "aarch64-cpu", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/03_hacky_hello_world/Cargo.toml b/03_hacky_hello_world/Cargo.toml index cca92834..a6d527c1 100644 --- a/03_hacky_hello_world/Cargo.toml +++ b/03_hacky_hello_world/Cargo.toml @@ -24,4 +24,4 @@ path = "src/main.rs" # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/03_hacky_hello_world/Makefile b/03_hacky_hello_world/Makefile index 49dcc1ed..ce5aff09 100644 --- a/03_hacky_hello_world/Makefile +++ b/03_hacky_hello_world/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -51,14 +52,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -81,7 +82,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -134,7 +134,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -185,7 +185,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -195,12 +194,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/03_hacky_hello_world/README.CN.md b/03_hacky_hello_world/README.CN.md new file mode 100644 index 00000000..ac08fae5 --- /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 index f52b226e..eafa3c21 100644 --- a/03_hacky_hello_world/README.ES.md +++ b/03_hacky_hello_world/README.ES.md @@ -31,292 +31,15 @@ Kernel panic: Stopping here. * *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 -```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 -@@ -24,7 +24,7 @@ - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 -- QEMU_RELEASE_ARGS = -d in_asm -display none -+ 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 -@@ -35,7 +35,7 @@ - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = -- QEMU_RELEASE_ARGS = -d in_asm -display none -+ 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 -@@ -71,17 +71,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) - - - -@@ -169,3 +172,28 @@ - ##------------------------------------------------------------------------------ - 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 colorecho, "\n$(QEMU_MISSING_STRING)") -+ -+else # QEMU is supported. -+ -+##------------------------------------------------------------------------------ -+## Run boot test -+##------------------------------------------------------------------------------ -+test_boot: $(KERNEL_BIN) -+ $(call colorecho, "\nBoot 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 -+++ 03_hacky_hello_world/src/bsp/raspberrypi/console.rs -@@ -0,0 +1,47 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2022 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 -uNr 02_runtime_init/src/bsp/raspberrypi.rs 03_hacky_hello_world/src/bsp/raspberrypi.rs ---- 02_runtime_init/src/bsp/raspberrypi.rs -+++ 03_hacky_hello_world/src/bsp/raspberrypi.rs -@@ -4,4 +4,5 @@ - - //! Top-level BSP file for the Raspberry Pi 3 and 4. - -+pub mod console; - 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 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2022 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 -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 -@@ -104,12 +104,16 @@ - //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. - //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. - -+#![feature(format_args_nl)] -+#![feature(panic_info_message)] - #![no_main] - #![no_std] - - mod bsp; -+mod console; - mod cpu; - mod panic_wait; -+mod print; - - /// Early init code. - /// -@@ -117,5 +121,7 @@ - /// - /// - Only a single core must be active and running this function. - unsafe fn kernel_init() -> ! { -- panic!() -+ println!("[0] Hello from Rust!"); -+ -+ panic!("Stopping here.") - } - -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 @@ - - //! A panic handler that infinitely waits. - --use crate::cpu; -+use crate::{cpu, println}; - use core::panic::PanicInfo; - - #[panic_handler] --fn panic(_info: &PanicInfo) -> ! { -+fn panic(info: &PanicInfo) -> ! { -+ if let Some(args) = info.message() { -+ println!("\nKernel panic: {}", args); -+ } else { -+ println!("\nKernel panic!"); -+ } -+ - cpu::wait_forever() - } - -diff -uNr 02_runtime_init/src/print.rs 03_hacky_hello_world/src/print.rs ---- 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-2022 Andre Richter -+ -+//! Printing. -+ -+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 -+#[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 -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' -``` +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 a1f3e150..07bf4503 100644 --- a/03_hacky_hello_world/README.md +++ b/03_hacky_hello_world/README.md @@ -2,16 +2,17 @@ ## 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 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!()` @@ -52,7 +53,7 @@ diff -uNr 02_runtime_init/Cargo.toml 03_hacky_hello_world/Cargo.toml diff -uNr 02_runtime_init/Makefile 03_hacky_hello_world/Makefile --- 02_runtime_init/Makefile +++ 03_hacky_hello_world/Makefile -@@ -24,7 +24,7 @@ +@@ -25,7 +25,7 @@ KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 @@ -61,7 +62,7 @@ diff -uNr 02_runtime_init/Makefile 03_hacky_hello_world/Makefile OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf -@@ -35,7 +35,7 @@ +@@ -36,7 +36,7 @@ KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = @@ -94,11 +95,10 @@ diff -uNr 02_runtime_init/Makefile 03_hacky_hello_world/Makefile -@@ -197,3 +200,28 @@ - ##------------------------------------------------------------------------------ - check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json -+ +@@ -191,3 +194,27 @@ + $(call color_header, "Launching nm") + @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + + +##-------------------------------------------------------------------------------------------------- @@ -130,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-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! BSP console facilities. + @@ -189,13 +189,15 @@ diff -uNr 02_runtime_init/src/bsp/raspberrypi.rs 03_hacky_hello_world/src/bsp/ra 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-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! System console. + ++use crate::bsp; ++ +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- @@ -209,14 +211,25 @@ 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 -@@ -104,12 +104,16 @@ - //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. +@@ -107,12 +107,16 @@ //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. + #![feature(asm_const)] +#![feature(format_args_nl)] +#![feature(panic_info_message)] #![no_main] @@ -230,7 +243,7 @@ diff -uNr 02_runtime_init/src/main.rs 03_hacky_hello_world/src/main.rs /// Early init code. /// -@@ -117,5 +121,7 @@ +@@ -120,5 +124,7 @@ /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { @@ -314,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-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Printing. + -+use crate::{bsp, console}; ++use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- @@ -329,7 +342,7 @@ 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. diff --git a/03_hacky_hello_world/src/_arch/aarch64/cpu.rs b/03_hacky_hello_world/src/_arch/aarch64/cpu.rs index 3b52e3a3..11d5024e 100644 --- a/03_hacky_hello_world/src/_arch/aarch64/cpu.rs +++ b/03_hacky_hello_world/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.rs b/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.rs index 2f9654c7..2a6c4649 100644 --- a/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.rs +++ b/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,8 +11,13 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.s b/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.s index 7d445a93..0011c607 100644 --- a/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.s +++ b/03_hacky_hello_world/src/_arch/aarch64/cpu/boot.s @@ -18,8 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -30,10 +28,10 @@ //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. - mrs x1, MPIDR_EL1 - and x1, x1, _core_id_mask - ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs - cmp x1, x2 + 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. diff --git a/03_hacky_hello_world/src/bsp.rs b/03_hacky_hello_world/src/bsp.rs index a09ba8a4..b128add9 100644 --- a/03_hacky_hello_world/src/bsp.rs +++ b/03_hacky_hello_world/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/03_hacky_hello_world/src/bsp/raspberrypi.rs b/03_hacky_hello_world/src/bsp/raspberrypi.rs index 6688a514..919d7e79 100644 --- a/03_hacky_hello_world/src/bsp/raspberrypi.rs +++ b/03_hacky_hello_world/src/bsp/raspberrypi.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. diff --git a/03_hacky_hello_world/src/bsp/raspberrypi/console.rs b/03_hacky_hello_world/src/bsp/raspberrypi/console.rs index 4cdf53ee..49d29370 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-2022 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 index 85fb89e4..65cf5abb 100644 --- a/03_hacky_hello_world/src/bsp/raspberrypi/cpu.rs +++ b/03_hacky_hello_world/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. 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 00000000..f6c18843 --- /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 007afd4a..00000000 --- a/03_hacky_hello_world/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,72 +0,0 @@ -/* 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 - .got : ALIGN(8) { *(.got) } :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 -} diff --git a/03_hacky_hello_world/src/console.rs b/03_hacky_hello_world/src/console.rs index 5ab4cc45..8b094dda 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-2022 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 b2a96010..13b89581 100644 --- a/03_hacky_hello_world/src/cpu.rs +++ b/03_hacky_hello_world/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/03_hacky_hello_world/src/cpu/boot.rs b/03_hacky_hello_world/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/03_hacky_hello_world/src/cpu/boot.rs +++ b/03_hacky_hello_world/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/03_hacky_hello_world/src/main.rs b/03_hacky_hello_world/src/main.rs index da450139..a38495a2 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-2022 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. //! @@ -104,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()`. +#![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] #![no_main] diff --git a/03_hacky_hello_world/src/panic_wait.rs b/03_hacky_hello_world/src/panic_wait.rs index fb30e8d4..5bb0896e 100644 --- a/03_hacky_hello_world/src/panic_wait.rs +++ b/03_hacky_hello_world/src/panic_wait.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. diff --git a/03_hacky_hello_world/src/print.rs b/03_hacky_hello_world/src/print.rs index 81c6d179..4e8c9b37 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-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -15,7 +15,7 @@ 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. diff --git a/04_safe_globals/.vscode/settings.json b/04_safe_globals/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/04_safe_globals/.vscode/settings.json +++ b/04_safe_globals/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index c8a669d9..3d196407 100644 --- a/04_safe_globals/Cargo.lock +++ b/04_safe_globals/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,11 +15,11 @@ dependencies = [ name = "mingo" version = "0.4.0" dependencies = [ - "cortex-a", + "aarch64-cpu", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/04_safe_globals/Cargo.toml b/04_safe_globals/Cargo.toml index cb51da55..1d8ee6a7 100644 --- a/04_safe_globals/Cargo.toml +++ b/04_safe_globals/Cargo.toml @@ -24,4 +24,4 @@ path = "src/main.rs" # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] -cortex-a = { version = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/04_safe_globals/Makefile b/04_safe_globals/Makefile index 49dcc1ed..ce5aff09 100644 --- a/04_safe_globals/Makefile +++ b/04_safe_globals/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -51,14 +52,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -81,7 +82,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -134,7 +134,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -185,7 +185,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -195,12 +194,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/04_safe_globals/README.CN.md b/04_safe_globals/README.CN.md new file mode 100644 index 00000000..eb35c006 --- /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 index b42be642..6418ef5b 100644 --- a/04_safe_globals/README.md +++ b/04_safe_globals/README.md @@ -148,7 +148,7 @@ diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi/console.rs 04_safe_globals/sr } Ok(()) -@@ -41,7 +80,37 @@ +@@ -41,7 +80,39 @@ // Public Code //-------------------------------------------------------------------------------------------------- @@ -164,9 +164,9 @@ diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi/console.rs 04_safe_globals/sr /// Return a reference to the console. -pub fn console() -> impl console::interface::Write { - QEMUOutput {} -+pub fn console() -> &'static impl console::interface::All { ++pub fn console() -> &'static dyn console::interface::All { + &QEMU_OUTPUT -+} + } + +//------------------------------------------------------------------------------ +// OS Interface Code @@ -177,7 +177,7 @@ diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi/console.rs 04_safe_globals/sr +/// 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 ++ // 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)) + } @@ -187,12 +187,14 @@ diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi/console.rs 04_safe_globals/sr + 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 -@@ -10,10 +10,22 @@ +@@ -12,12 +12,24 @@ /// Console interfaces. pub mod interface { @@ -218,21 +220,31 @@ diff -uNr 03_hacky_hello_world/src/console.rs 04_safe_globals/src/console.rs + } + + /// Trait alias for a full-fledged console. -+ pub trait All = Write + Statistics; ++ 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 -@@ -106,6 +106,7 @@ - +@@ -109,6 +109,7 @@ + #![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] +#![feature(trait_alias)] #![no_main] #![no_std] -@@ -114,6 +115,7 @@ +@@ -117,6 +118,7 @@ mod cpu; mod panic_wait; mod print; @@ -240,32 +252,42 @@ diff -uNr 03_hacky_hello_world/src/main.rs 04_safe_globals/src/main.rs /// Early init code. /// -@@ -121,7 +123,15 @@ +@@ -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::interface::Statistics; ++ use console::console; - panic!("Stopping here.") + println!("[0] Hello from Rust!"); + -+ println!( -+ "[1] Chars written: {}", -+ bsp::console::console().chars_written() -+ ); ++ 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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! @@ -291,7 +313,7 @@ diff -uNr 03_hacky_hello_world/src/synchronization.rs 04_safe_globals/src/synchr + 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; + } +} + @@ -332,7 +354,7 @@ diff -uNr 03_hacky_hello_world/src/synchronization.rs 04_safe_globals/src/synchr +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/04_safe_globals/src/_arch/aarch64/cpu.rs b/04_safe_globals/src/_arch/aarch64/cpu.rs index 3b52e3a3..11d5024e 100644 --- a/04_safe_globals/src/_arch/aarch64/cpu.rs +++ b/04_safe_globals/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/04_safe_globals/src/_arch/aarch64/cpu/boot.rs b/04_safe_globals/src/_arch/aarch64/cpu/boot.rs index 2f9654c7..2a6c4649 100644 --- a/04_safe_globals/src/_arch/aarch64/cpu/boot.rs +++ b/04_safe_globals/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,8 +11,13 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/04_safe_globals/src/_arch/aarch64/cpu/boot.s b/04_safe_globals/src/_arch/aarch64/cpu/boot.s index 7d445a93..0011c607 100644 --- a/04_safe_globals/src/_arch/aarch64/cpu/boot.s +++ b/04_safe_globals/src/_arch/aarch64/cpu/boot.s @@ -18,8 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -30,10 +28,10 @@ //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. - mrs x1, MPIDR_EL1 - and x1, x1, _core_id_mask - ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs - cmp x1, x2 + 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. diff --git a/04_safe_globals/src/bsp.rs b/04_safe_globals/src/bsp.rs index a09ba8a4..b128add9 100644 --- a/04_safe_globals/src/bsp.rs +++ b/04_safe_globals/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/04_safe_globals/src/bsp/raspberrypi.rs b/04_safe_globals/src/bsp/raspberrypi.rs index 6688a514..919d7e79 100644 --- a/04_safe_globals/src/bsp/raspberrypi.rs +++ b/04_safe_globals/src/bsp/raspberrypi.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. diff --git a/04_safe_globals/src/bsp/raspberrypi/console.rs b/04_safe_globals/src/bsp/raspberrypi/console.rs index f471cebb..753cbcb6 100644 --- a/04_safe_globals/src/bsp/raspberrypi/console.rs +++ b/04_safe_globals/src/bsp/raspberrypi/console.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP console facilities. @@ -90,7 +90,7 @@ impl QEMUOutput { } /// Return a reference to the console. -pub fn console() -> &'static impl console::interface::All { +pub fn console() -> &'static dyn console::interface::All { &QEMU_OUTPUT } @@ -103,7 +103,7 @@ use synchronization::interface::Mutex; /// 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 + // 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)) } @@ -114,3 +114,5 @@ impl console::interface::Statistics for QEMUOutput { 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 index 85fb89e4..65cf5abb 100644 --- a/04_safe_globals/src/bsp/raspberrypi/cpu.rs +++ b/04_safe_globals/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. 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 00000000..f6c18843 --- /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/bsp/raspberrypi/link.ld b/04_safe_globals/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 007afd4a..00000000 --- a/04_safe_globals/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,72 +0,0 @@ -/* 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 - .got : ALIGN(8) { *(.got) } :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 -} diff --git a/04_safe_globals/src/console.rs b/04_safe_globals/src/console.rs index 3894c18d..d41c95a1 100644 --- a/04_safe_globals/src/console.rs +++ b/04_safe_globals/src/console.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +use crate::bsp; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -27,5 +29,16 @@ pub mod interface { } /// Trait alias for a full-fledged console. - pub trait All = Write + Statistics; + 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 index b2a96010..13b89581 100644 --- a/04_safe_globals/src/cpu.rs +++ b/04_safe_globals/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/04_safe_globals/src/cpu/boot.rs b/04_safe_globals/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/04_safe_globals/src/cpu/boot.rs +++ b/04_safe_globals/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/04_safe_globals/src/main.rs b/04_safe_globals/src/main.rs index 450ae1ff..4c5a7e0d 100644 --- a/04_safe_globals/src/main.rs +++ b/04_safe_globals/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -104,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()`. +#![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] #![feature(trait_alias)] @@ -123,14 +126,11 @@ mod synchronization; /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { - use console::interface::Statistics; + use console::console; println!("[0] Hello from Rust!"); - println!( - "[1] Chars written: {}", - bsp::console::console().chars_written() - ); + 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 index fb30e8d4..5bb0896e 100644 --- a/04_safe_globals/src/panic_wait.rs +++ b/04_safe_globals/src/panic_wait.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. diff --git a/04_safe_globals/src/print.rs b/04_safe_globals/src/print.rs index 81c6d179..6de99572 100644 --- a/04_safe_globals/src/print.rs +++ b/04_safe_globals/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. diff --git a/04_safe_globals/src/synchronization.rs b/04_safe_globals/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/04_safe_globals/src/synchronization.rs +++ b/04_safe_globals/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/05_drivers_gpio_uart/.vscode/settings.json b/05_drivers_gpio_uart/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/05_drivers_gpio_uart/.vscode/settings.json +++ b/05_drivers_gpio_uart/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index caf94f7c..4514e882 100644 --- a/05_drivers_gpio_uart/Cargo.lock +++ b/05_drivers_gpio_uart/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,12 +15,12 @@ dependencies = [ name = "mingo" version = "0.5.0" dependencies = [ - "cortex-a", + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/05_drivers_gpio_uart/Cargo.toml b/05_drivers_gpio_uart/Cargo.toml index b2f17d8d..c431e438 100644 --- a/05_drivers_gpio_uart/Cargo.toml +++ b/05_drivers_gpio_uart/Cargo.toml @@ -23,8 +23,8 @@ path = "src/main.rs" [dependencies] # Optional dependencies -tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/05_drivers_gpio_uart/Makefile b/05_drivers_gpio_uart/Makefile index 28702bc8..f5135d1e 100644 --- a/05_drivers_gpio_uart/Makefile +++ b/05_drivers_gpio_uart/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -54,14 +55,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -84,7 +85,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -146,11 +146,11 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation -##------------------------------------------------------------------------------ +##----------------------------------------------------------------------------- doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open @@ -204,7 +204,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -214,12 +213,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/05_drivers_gpio_uart/README.CN.md b/05_drivers_gpio_uart/README.CN.md new file mode 100644 index 00000000..7999da7b --- /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 index ccd4575e..5e96d40a 100644 --- a/05_drivers_gpio_uart/README.md +++ b/05_drivers_gpio_uart/README.md @@ -2,41 +2,81 @@ ## 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 (that is, routing signals from inside the `SoC` - to actual HW pins) the RPi's PL011 UART. - - Note how this driver differentiates between **RPi 3** and **RPi4**. Their HW is different, - so we have to account for it in SW. - - 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 respective device - 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. +- 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 -Some steps for preparing the SD card differ between RPi3 and RPi4, so be careful. +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 @@ -47,7 +87,7 @@ Some steps for preparing the SD card differ between RPi3 and RPi4, so be careful arm_64bit=1 init_uart_clock=48000000 ``` -### Pi 3 +### 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) @@ -55,7 +95,7 @@ init_uart_clock=48000000 - [start.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start.elf) 4. Run `make`. -### Pi 4 +### 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) @@ -64,7 +104,7 @@ init_uart_clock=48000000 4. Run `BSP=rpi4 make`. -_**Note**: Should it not work on your RPi4, try renaming `start4.elf` to `start.elf` (without the 4) +_**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 @@ -87,6 +127,7 @@ $ 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: @@ -98,8 +139,8 @@ Miniterm 1.0 [0] mingo version 0.5.0 [1] Booting on: Raspberry Pi 3 [2] Drivers loaded: - 1. BCM GPIO - 2. BCM PL011 UART + 1. BCM PL011 UART + 2. BCM GPIO [3] Chars written: 117 [4] Echoing input now ``` @@ -136,16 +177,16 @@ diff -uNr 04_safe_globals/Cargo.toml 05_drivers_gpio_uart/Cargo.toml [dependencies] +# Optional dependencies -+tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } + 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 -@@ -12,6 +12,9 @@ +@@ -13,6 +13,9 @@ # Default to the RPi3. BSP ?= rpi3 @@ -234,10 +275,10 @@ diff -uNr 04_safe_globals/src/_arch/aarch64/cpu.rs 05_drivers_gpio_uart/src/_arc 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,225 @@ +@@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + @@ -345,16 +386,13 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 05_drivers_g +/// 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 { @@ -362,7 +400,7 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 05_drivers_g +} + +//-------------------------------------------------------------------------------------------------- -+// Public Code ++// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { @@ -385,7 +423,7 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 05_drivers_g + // 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. ++ // - 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 @@ -432,7 +470,13 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 05_drivers_g + } +} + ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ +impl GPIO { ++ pub const COMPATIBLE: &'static str = "BCM GPIO"; ++ + /// Create an instance. + /// + /// # Safety @@ -457,17 +501,17 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 05_drivers_g + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { -+ "BCM GPIO" ++ 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,402 @@ +@@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! @@ -634,18 +678,15 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 05_dri + NonBlocking, +} + -+//-------------------------------------------------------------------------------------------------- -+// Public Definitions -+//-------------------------------------------------------------------------------------------------- -+ -+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 { @@ -653,7 +694,7 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 05_dri +} + +//-------------------------------------------------------------------------------------------------- -+// Public Code ++// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { @@ -793,7 +834,13 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 05_dri + } +} + ++//-------------------------------------------------------------------------------------------------- ++// Public Code ++//-------------------------------------------------------------------------------------------------- ++ +impl PL011Uart { ++ pub const COMPATIBLE: &'static str = "BCM PL011 UART"; ++ + /// Create an instance. + /// + /// # Safety @@ -813,7 +860,7 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 05_dri + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { -+ "BCM PL011 UART" ++ Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { @@ -831,7 +878,7 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 05_dri + } + + 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)) + } @@ -867,6 +914,8 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 05_dri + 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 @@ -874,7 +923,7 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/bcm.rs 05_drivers_gpio_uart/src/ @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + @@ -890,7 +939,7 @@ diff -uNr 04_safe_globals/src/bsp/device_driver/common.rs 05_drivers_gpio_uart/s @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2020-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + @@ -933,7 +982,7 @@ diff -uNr 04_safe_globals/src/bsp/device_driver.rs 05_drivers_gpio_uart/src/bsp/ @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + @@ -947,24 +996,19 @@ diff -uNr 04_safe_globals/src/bsp/device_driver.rs 05_drivers_gpio_uart/src/bsp/ 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,113 +4,34 @@ +@@ -4,115 +4,13 @@ //! BSP console facilities. -use crate::{console, synchronization, synchronization::NullLock}; -+use super::memory; -+use crate::{bsp::device_driver, console}; - use core::fmt; - - //-------------------------------------------------------------------------------------------------- +-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, @@ -1007,13 +1051,9 @@ diff -uNr 04_safe_globals/src/bsp/raspberrypi/console.rs 05_drivers_gpio_uart/sr -/// 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 @@ -1031,11 +1071,12 @@ diff -uNr 04_safe_globals/src/bsp/raspberrypi/console.rs 05_drivers_gpio_uart/sr - Ok(()) - } -} -- --//-------------------------------------------------------------------------------------------------- --// Public Code --//-------------------------------------------------------------------------------------------------- -- ++use crate::console; + + //-------------------------------------------------------------------------------------------------- + // Public Code + //-------------------------------------------------------------------------------------------------- + -impl QEMUOutput { - /// Create a new instance. - pub const fn new() -> QEMUOutput { @@ -1043,18 +1084,10 @@ diff -uNr 04_safe_globals/src/bsp/raspberrypi/console.rs 05_drivers_gpio_uart/sr - 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 { + pub fn console() -> &'static dyn console::interface::All { - &QEMU_OUTPUT -} - @@ -1067,7 +1100,7 @@ diff -uNr 04_safe_globals/src/bsp/raspberrypi/console.rs 05_drivers_gpio_uart/sr -/// 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 +- // 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)) - } @@ -1077,61 +1110,85 @@ diff -uNr 04_safe_globals/src/bsp/raspberrypi/console.rs 05_drivers_gpio_uart/sr - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } -+ &super::PL011_UART ++ &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,49 @@ +@@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 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 -uNr 04_safe_globals/src/bsp/raspberrypi/memory.rs 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs @@ -1140,7 +1197,7 @@ diff -uNr 04_safe_globals/src/bsp/raspberrypi/memory.rs 05_drivers_gpio_uart/src @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. + @@ -1179,25 +1236,16 @@ diff -uNr 04_safe_globals/src/bsp/raspberrypi/memory.rs 05_drivers_gpio_uart/src 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 -@@ -6,3 +6,33 @@ +@@ -4,5 +4,23 @@ + + //! Top-level BSP file for the Raspberry Pi 3 and 4. - pub mod console; +-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 +//-------------------------------------------------------------------------------------------------- + @@ -1227,10 +1275,67 @@ diff -uNr 04_safe_globals/src/bsp.rs 05_drivers_gpio_uart/src/bsp.rs 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 -@@ -14,8 +14,25 @@ +@@ -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 { @@ -1256,7 +1361,7 @@ diff -uNr 04_safe_globals/src/console.rs 05_drivers_gpio_uart/src/console.rs } /// Console statistics. -@@ -24,8 +41,13 @@ +@@ -26,19 +45,37 @@ fn chars_written(&self) -> usize { 0 } @@ -1268,8 +1373,34 @@ diff -uNr 04_safe_globals/src/console.rs 05_drivers_gpio_uart/src/console.rs } /// Trait alias for a full-fledged console. -- pub trait All = Write + Statistics; -+ pub trait All = Write + Read + Statistics; +- 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 @@ -1288,13 +1419,29 @@ diff -uNr 04_safe_globals/src/cpu.rs 05_drivers_gpio_uart/src/cpu.rs 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,44 @@ +@@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// 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 +//-------------------------------------------------------------------------------------------------- @@ -1315,37 +1462,144 @@ diff -uNr 04_safe_globals/src/driver.rs 05_drivers_gpio_uart/src/driver.rs + 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(); + -+ /// Device driver management functions. ++//-------------------------------------------------------------------------------------------------- ++// 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 ++ ); ++ } ++ } ++ }); ++ } ++ ++ /// 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 -@@ -104,6 +104,7 @@ +@@ -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)] - #![feature(trait_alias)] -@@ -113,6 +114,7 @@ +@@ -116,6 +117,7 @@ mod bsp; mod console; mod cpu; @@ -1353,34 +1607,34 @@ diff -uNr 04_safe_globals/src/main.rs 05_drivers_gpio_uart/src/main.rs mod panic_wait; mod print; mod synchronization; -@@ -122,16 +124,54 @@ +@@ -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::interface::Statistics; -+ use driver::interface::DriverManager; - -- println!("[0] Hello from Rust!"); -+ for i in bsp::driver::driver_manager().all_device_drivers().iter() { -+ if let Err(x) = i.init() { -+ panic!("Error loading driver: {}: {}", i.compatible(), x); -+ } +- use console::console; ++ // 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(); -+ // println! is usable from here on. + ++ // 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 bsp::console::console; -+ use console::interface::All; -+ use driver::interface::DriverManager; -+ ++ use console::console; + +- println!("[2] Stopping here."); +- cpu::wait_forever() + println!( + "[0] {} version {}", + env!("CARGO_PKG_NAME"), @@ -1389,76 +1643,19 @@ diff -uNr 04_safe_globals/src/main.rs 05_drivers_gpio_uart/src/main.rs + println!("[1] Booting on: {}", bsp::board_name()); + + println!("[2] Drivers loaded:"); -+ for (i, driver) in bsp::driver::driver_manager() -+ .all_device_drivers() -+ .iter() -+ .enumerate() -+ { -+ println!(" {}. {}", i + 1, driver.compatible()); -+ } - - println!( -- "[1] Chars written: {}", -+ "[3] Chars written: {}", - bsp::console::console().chars_written() - ); ++ driver::driver_manager().enumerate(); ++ ++ println!("[3] Chars written: {}", console().chars_written()); + println!("[4] Echoing input now"); - -- println!("[2] Stopping here."); -- cpu::wait_forever() ++ + // Discard any spurious received characters before going into echo mode. + console().clear_rx(); + loop { -+ let c = bsp::console::console().read_char(); -+ bsp::console::console().write_char(c); ++ let c = console().read_char(); ++ console().write_char(c); + } } -diff -uNr 04_safe_globals/src/panic_wait.rs 05_drivers_gpio_uart/src/panic_wait.rs ---- 04_safe_globals/src/panic_wait.rs -+++ 05_drivers_gpio_uart/src/panic_wait.rs -@@ -4,13 +4,29 @@ - - //! 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 -+#[macro_export] -+macro_rules! panic_println { -+ ($($arg:tt)*) => ({ -+ _panic_print(format_args_nl!($($arg)*)); -+ }) -+} -+ - /// Stop immediately if called a second time. - /// - /// # Note -@@ -50,7 +66,7 @@ - _ => ("???", 0, 0), - }; - -- println!( -+ panic_println!( - "Kernel panic!\n\n\ - Panic location:\n File '{}', line {}, column {}\n\n\ - {}", - 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 diff --git a/05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs b/05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs index 2ef860d2..f1f1e9af 100644 --- a/05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs +++ b/05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.rs b/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.rs index 2f9654c7..2a6c4649 100644 --- a/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.rs +++ b/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,8 +11,13 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s b/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s index 7d445a93..0011c607 100644 --- a/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s +++ b/05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s @@ -18,8 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -30,10 +28,10 @@ //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. - mrs x1, MPIDR_EL1 - and x1, x1, _core_id_mask - ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs - cmp x1, x2 + 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. diff --git a/05_drivers_gpio_uart/src/bsp.rs b/05_drivers_gpio_uart/src/bsp.rs index 824787f6..246973bc 100644 --- a/05_drivers_gpio_uart/src/bsp.rs +++ b/05_drivers_gpio_uart/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/05_drivers_gpio_uart/src/bsp/device_driver.rs b/05_drivers_gpio_uart/src/bsp/device_driver.rs index 6e9bf8f3..64049a4c 100644 --- a/05_drivers_gpio_uart/src/bsp/device_driver.rs +++ b/05_drivers_gpio_uart/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs b/05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs index b4b7906e..1c343d1d 100644 --- a/05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs +++ b/05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. 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 index 76ce3bd1..920b4c00 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -148,7 +145,7 @@ impl GPIOInner { // 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. + // - 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 @@ -195,7 +192,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -220,6 +223,6 @@ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { - "BCM GPIO" + 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 index 878ea567..d92612ea 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -326,7 +323,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -346,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> { @@ -364,7 +367,7 @@ 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)) } @@ -400,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/05_drivers_gpio_uart/src/bsp/device_driver/common.rs b/05_drivers_gpio_uart/src/bsp/device_driver/common.rs index fd9e988e..dfe7d8ef 100644 --- a/05_drivers_gpio_uart/src/bsp/device_driver/common.rs +++ b/05_drivers_gpio_uart/src/bsp/device_driver/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi.rs index 22edb4fa..3ea864dc 100644 --- a/05_drivers_gpio_uart/src/bsp/raspberrypi.rs +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi.rs @@ -1,25 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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) }; - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs index a247032f..0d585229 100644 --- a/05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs @@ -1,37 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP console facilities. -use super::memory; -use crate::{bsp::device_driver, console}; -use core::fmt; +use crate::console; //-------------------------------------------------------------------------------------------------- // 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 +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 index 85fb89e4..65cf5abb 100644 --- a/05_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs index b5538baa..2a80ee2c 100644 --- a/05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs @@ -1,49 +1,71 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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/05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld b/05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 00000000..f6c18843 --- /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/link.ld b/05_drivers_gpio_uart/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 007afd4a..00000000 --- a/05_drivers_gpio_uart/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,72 +0,0 @@ -/* 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 - .got : ALIGN(8) { *(.got) } :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 -} diff --git a/05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs b/05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs index 27be8590..cdca14b8 100644 --- a/05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs +++ b/05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. diff --git a/05_drivers_gpio_uart/src/console.rs b/05_drivers_gpio_uart/src/console.rs index e49e241f..a83f86fe 100644 --- a/05_drivers_gpio_uart/src/console.rs +++ b/05_drivers_gpio_uart/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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/05_drivers_gpio_uart/src/console/null_console.rs b/05_drivers_gpio_uart/src/console/null_console.rs new file mode 100644 index 00000000..e92a022b --- /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 index 6ccee456..eacb8924 100644 --- a/05_drivers_gpio_uart/src/cpu.rs +++ b/05_drivers_gpio_uart/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/05_drivers_gpio_uart/src/cpu/boot.rs b/05_drivers_gpio_uart/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/05_drivers_gpio_uart/src/cpu/boot.rs +++ b/05_drivers_gpio_uart/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/05_drivers_gpio_uart/src/driver.rs b/05_drivers_gpio_uart/src/driver.rs index 2fcc7562..feef34e2 100644 --- a/05_drivers_gpio_uart/src/driver.rs +++ b/05_drivers_gpio_uart/src/driver.rs @@ -1,9 +1,25 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// 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 //-------------------------------------------------------------------------------------------------- @@ -24,21 +40,128 @@ 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>; + +/// 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()), + } + } - /// Device driver management functions. + /// 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 + ); + } + } + }); + } + + /// 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 index 70e6b116..11d342ce 100644 --- a/05_drivers_gpio_uart/src/main.rs +++ b/05_drivers_gpio_uart/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -105,6 +107,7 @@ //! 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)] @@ -126,14 +129,13 @@ mod synchronization; /// - 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. @@ -142,9 +144,7 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; - use driver::interface::DriverManager; + use console::console; println!( "[0] {} version {}", @@ -154,24 +154,15 @@ fn kernel_main() -> ! { println!("[1] Booting on: {}", bsp::board_name()); println!("[2] Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - println!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); - println!( - "[3] Chars written: {}", - bsp::console::console().chars_written() - ); + 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 = bsp::console::console().read_char(); - bsp::console::console().write_char(c); + 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 index e546b06d..5bb0896e 100644 --- a/05_drivers_gpio_uart/src/panic_wait.rs +++ b/05_drivers_gpio_uart/src/panic_wait.rs @@ -1,32 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -66,7 +50,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/05_drivers_gpio_uart/src/print.rs b/05_drivers_gpio_uart/src/print.rs index 81c6d179..6de99572 100644 --- a/05_drivers_gpio_uart/src/print.rs +++ b/05_drivers_gpio_uart/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. diff --git a/05_drivers_gpio_uart/src/synchronization.rs b/05_drivers_gpio_uart/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/05_drivers_gpio_uart/src/synchronization.rs +++ b/05_drivers_gpio_uart/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/06_uart_chainloader/.vscode/settings.json b/06_uart_chainloader/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/06_uart_chainloader/.vscode/settings.json +++ b/06_uart_chainloader/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index a92a3ab5..047875fe 100644 --- a/06_uart_chainloader/Cargo.lock +++ b/06_uart_chainloader/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,12 +15,12 @@ dependencies = [ name = "mingo" version = "0.6.0" dependencies = [ - "cortex-a", + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/06_uart_chainloader/Cargo.toml b/06_uart_chainloader/Cargo.toml index f00c87a8..27b413a2 100644 --- a/06_uart_chainloader/Cargo.toml +++ b/06_uart_chainloader/Cargo.toml @@ -23,8 +23,8 @@ path = "src/main.rs" [dependencies] # Optional dependencies -tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/06_uart_chainloader/Makefile b/06_uart_chainloader/Makefile index b3af24c5..3366de31 100644 --- a/06_uart_chainloader/Makefile +++ b/06_uart_chainloader/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -56,14 +57,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -86,7 +87,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -148,7 +148,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -210,7 +210,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -220,12 +219,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/06_uart_chainloader/README.CN.md b/06_uart_chainloader/README.CN.md new file mode 100644 index 00000000..de7f5111 --- /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 index f07131ec..5e4efe25 100644 --- a/06_uart_chainloader/README.md +++ b/06_uart_chainloader/README.md @@ -17,8 +17,8 @@ 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 `link.ld`). The binary then copies itself from loaded to linked address -(aka "relocating" itself), and then jumps to the relocated version of `_start_rust()`. +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, @@ -27,8 +27,9 @@ 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_. +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 @@ -65,6 +66,7 @@ Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now + __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | @@ -73,14 +75,14 @@ Minipush 1.0 Raspberry Pi 3 [ML] Requesting binary -[MP] ⏩ Pushing 6 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 +[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 GPIO - 2. BCM PL011 UART + 1. BCM PL011 UART + 2. BCM GPIO [3] Chars written: 117 [4] Echoing input now ``` @@ -138,7 +140,7 @@ Binary files 05_drivers_gpio_uart/demo_payload_rpi4.img and 06_uart_chainloader/ diff -uNr 05_drivers_gpio_uart/Makefile 06_uart_chainloader/Makefile --- 05_drivers_gpio_uart/Makefile +++ 06_uart_chainloader/Makefile -@@ -23,27 +23,29 @@ +@@ -24,27 +24,29 @@ QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) @@ -235,7 +237,6 @@ diff -uNr 05_drivers_gpio_uart/Makefile 06_uart_chainloader/Makefile + @$(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 @@ -247,7 +248,7 @@ diff -uNr 05_drivers_gpio_uart/Makefile 06_uart_chainloader/Makefile ##------------------------------------------------------------------------------ ## Run clippy -@@ -239,7 +245,8 @@ +@@ -232,7 +238,8 @@ ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @@ -276,10 +277,10 @@ diff -uNr 05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s 06_uart_chainloader/ + movk \register, #:abs_g0_nc:\symbol +.endm + - .equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- -@@ -39,23 +50,35 @@ + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -37,23 +48,35 @@ // If execution reaches here, it is the boot core. // Initialize DRAM. @@ -323,23 +324,10 @@ diff -uNr 05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s 06_uart_chainloader/ // Infinitely wait for events (aka "park the core"). .L_parking_loop: -diff -uNr 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ---- 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -+++ 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -@@ -148,7 +148,7 @@ - // 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. -+ // - 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 - 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 -@@ -278,7 +278,7 @@ +@@ -275,7 +275,7 @@ } /// Retrieve a character. @@ -348,7 +336,7 @@ diff -uNr 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 0 // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. -@@ -293,12 +293,7 @@ +@@ -290,12 +290,7 @@ } // Read one character. @@ -362,7 +350,7 @@ diff -uNr 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 0 // Update statistics. self.chars_read += 1; -@@ -378,14 +373,14 @@ +@@ -381,14 +376,14 @@ impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner @@ -380,11 +368,32 @@ diff -uNr 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 0 {} } -diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/link.ld 06_uart_chainloader/src/bsp/raspberrypi/link.ld ---- 05_drivers_gpio_uart/src/bsp/raspberrypi/link.ld -+++ 06_uart_chainloader/src/bsp/raspberrypi/link.ld +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-2022 Andre Richter + * Copyright (c) 2018-2023 Andre Richter */ -__rpi_phys_dram_start_addr = 0; @@ -410,7 +419,7 @@ diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/link.ld 06_uart_chainloader/s .text : { KEEP(*(.text._start)) -@@ -61,6 +61,10 @@ +@@ -60,6 +60,10 @@ ***********************************************************************************************/ .data : { *(.data*) } :segment_data @@ -425,19 +434,14 @@ diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/link.ld 06_uart_chainloader/s 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,9 +11,10 @@ +@@ -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; -+ pub const GPIO_OFFSET: usize = 0x0020_0000; -+ pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] + 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; } @@ -453,10 +457,41 @@ diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs 06_uart_chainloader + 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 -@@ -140,38 +140,56 @@ +@@ -142,27 +142,55 @@ kernel_main() } @@ -469,9 +504,7 @@ diff -uNr 05_drivers_gpio_uart/src/main.rs 06_uart_chainloader/src/main.rs + /// The main function running after the early init. fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; -- use driver::interface::DriverManager; + use console::console; - println!( - "[0] {} version {}", @@ -479,44 +512,35 @@ diff -uNr 05_drivers_gpio_uart/src/main.rs 06_uart_chainloader/src/main.rs - env!("CARGO_PKG_VERSION") - ); - println!("[1] Booting on: {}", bsp::board_name()); -- -- println!("[2] Drivers loaded:"); -- for (i, driver) in bsp::driver::driver_manager() -- .all_device_drivers() -- .iter() -- .enumerate() -- { -- println!(" {}. {}", i + 1, driver.compatible()); + 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); - } ++ } -- println!( -- "[3] Chars written: {}", -- bsp::console::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); + // 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; - -- // Discard any spurious received characters before going into echo mode. -- console().clear_rx(); -- loop { -- let c = bsp::console::console().read_char(); -- bsp::console::console().write_char(c); ++ + // Trust it's not too big. + console().write_char('O'); + console().write_char('K'); @@ -555,7 +579,7 @@ diff -uNr 05_drivers_gpio_uart/tests/chainboot_test.rb 06_uart_chainloader/tests + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# -+# Copyright (c) 2020-2022 Andre Richter ++# Copyright (c) 2020-2023 Andre Richter + +require_relative '../../common/serial/minipush' +require_relative '../../common/tests/boot_test' diff --git a/06_uart_chainloader/demo_payload_rpi3.img b/06_uart_chainloader/demo_payload_rpi3.img index b422ad25..8109de38 100755 Binary files a/06_uart_chainloader/demo_payload_rpi3.img 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 index 173debe6..807da95b 100755 Binary files a/06_uart_chainloader/demo_payload_rpi4.img 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 index 2ef860d2..f1f1e9af 100644 --- a/06_uart_chainloader/src/_arch/aarch64/cpu.rs +++ b/06_uart_chainloader/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/06_uart_chainloader/src/_arch/aarch64/cpu/boot.rs b/06_uart_chainloader/src/_arch/aarch64/cpu/boot.rs index 2f9654c7..2a6c4649 100644 --- a/06_uart_chainloader/src/_arch/aarch64/cpu/boot.rs +++ b/06_uart_chainloader/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,8 +11,13 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/06_uart_chainloader/src/_arch/aarch64/cpu/boot.s b/06_uart_chainloader/src/_arch/aarch64/cpu/boot.s index 74dcdfbe..3ed0d494 100644 --- a/06_uart_chainloader/src/_arch/aarch64/cpu/boot.s +++ b/06_uart_chainloader/src/_arch/aarch64/cpu/boot.s @@ -29,8 +29,6 @@ movk \register, #:abs_g0_nc:\symbol .endm -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -41,10 +39,10 @@ //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. - mrs x1, MPIDR_EL1 - and x1, x1, _core_id_mask - ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs - cmp x1, x2 + 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. diff --git a/06_uart_chainloader/src/bsp.rs b/06_uart_chainloader/src/bsp.rs index 824787f6..246973bc 100644 --- a/06_uart_chainloader/src/bsp.rs +++ b/06_uart_chainloader/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/06_uart_chainloader/src/bsp/device_driver.rs b/06_uart_chainloader/src/bsp/device_driver.rs index 6e9bf8f3..64049a4c 100644 --- a/06_uart_chainloader/src/bsp/device_driver.rs +++ b/06_uart_chainloader/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/06_uart_chainloader/src/bsp/device_driver/bcm.rs b/06_uart_chainloader/src/bsp/device_driver/bcm.rs index b4b7906e..1c343d1d 100644 --- a/06_uart_chainloader/src/bsp/device_driver/bcm.rs +++ b/06_uart_chainloader/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. 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 index 5c68107a..920b4c00 100644 --- a/06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ b/06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -195,7 +192,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -220,6 +223,6 @@ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { - "BCM GPIO" + 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 index e6b4a952..50a069ea 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -321,7 +318,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -341,7 +344,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> { @@ -359,7 +362,7 @@ 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)) } @@ -395,3 +398,5 @@ impl console::interface::Statistics for PL011Uart { 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 index fd9e988e..dfe7d8ef 100644 --- a/06_uart_chainloader/src/bsp/device_driver/common.rs +++ b/06_uart_chainloader/src/bsp/device_driver/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/06_uart_chainloader/src/bsp/raspberrypi.rs b/06_uart_chainloader/src/bsp/raspberrypi.rs index 22edb4fa..3ea864dc 100644 --- a/06_uart_chainloader/src/bsp/raspberrypi.rs +++ b/06_uart_chainloader/src/bsp/raspberrypi.rs @@ -1,25 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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) }; - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- diff --git a/06_uart_chainloader/src/bsp/raspberrypi/console.rs b/06_uart_chainloader/src/bsp/raspberrypi/console.rs deleted file mode 100644 index a247032f..00000000 --- a/06_uart_chainloader/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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_uart_chainloader/src/bsp/raspberrypi/cpu.rs b/06_uart_chainloader/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/06_uart_chainloader/src/bsp/raspberrypi/cpu.rs +++ b/06_uart_chainloader/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. diff --git a/06_uart_chainloader/src/bsp/raspberrypi/driver.rs b/06_uart_chainloader/src/bsp/raspberrypi/driver.rs index b5538baa..2a80ee2c 100644 --- a/06_uart_chainloader/src/bsp/raspberrypi/driver.rs +++ b/06_uart_chainloader/src/bsp/raspberrypi/driver.rs @@ -1,49 +1,71 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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/06_uart_chainloader/src/bsp/raspberrypi/link.ld b/06_uart_chainloader/src/bsp/raspberrypi/kernel.ld similarity index 88% rename from 06_uart_chainloader/src/bsp/raspberrypi/link.ld rename to 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld index 4fd5bf6a..c84b6238 100644 --- a/06_uart_chainloader/src/bsp/raspberrypi/link.ld +++ b/06_uart_chainloader/src/bsp/raspberrypi/kernel.ld @@ -54,7 +54,6 @@ SECTIONS } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code /*********************************************************************************************** * Data + BSS @@ -73,4 +72,12 @@ SECTIONS . = 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 index 0959bdce..ee72b27a 100644 --- a/06_uart_chainloader/src/bsp/raspberrypi/memory.rs +++ b/06_uart_chainloader/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. @@ -13,8 +13,8 @@ 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; + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] diff --git a/06_uart_chainloader/src/console.rs b/06_uart_chainloader/src/console.rs index e49e241f..a83f86fe 100644 --- a/06_uart_chainloader/src/console.rs +++ b/06_uart_chainloader/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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/06_uart_chainloader/src/console/null_console.rs b/06_uart_chainloader/src/console/null_console.rs new file mode 100644 index 00000000..e92a022b --- /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 index 6ccee456..eacb8924 100644 --- a/06_uart_chainloader/src/cpu.rs +++ b/06_uart_chainloader/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/06_uart_chainloader/src/cpu/boot.rs b/06_uart_chainloader/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/06_uart_chainloader/src/cpu/boot.rs +++ b/06_uart_chainloader/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/06_uart_chainloader/src/driver.rs b/06_uart_chainloader/src/driver.rs index 2fcc7562..53592c66 100644 --- a/06_uart_chainloader/src/driver.rs +++ b/06_uart_chainloader/src/driver.rs @@ -1,9 +1,22 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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/06_uart_chainloader/src/main.rs b/06_uart_chainloader/src/main.rs index 32a56bda..dd82ec3f 100644 --- a/06_uart_chainloader/src/main.rs +++ b/06_uart_chainloader/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -105,6 +107,7 @@ //! 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)] @@ -126,14 +129,13 @@ mod synchronization; /// - 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. @@ -149,8 +151,7 @@ const MINILOAD_LOGO: &str = r#" /// The main function running after the early init. fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; + use console::console; println!("{}", MINILOAD_LOGO); println!("{:^37}", bsp::board_name()); diff --git a/06_uart_chainloader/src/panic_wait.rs b/06_uart_chainloader/src/panic_wait.rs index e546b06d..5bb0896e 100644 --- a/06_uart_chainloader/src/panic_wait.rs +++ b/06_uart_chainloader/src/panic_wait.rs @@ -1,32 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -66,7 +50,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/06_uart_chainloader/src/print.rs b/06_uart_chainloader/src/print.rs index 81c6d179..6de99572 100644 --- a/06_uart_chainloader/src/print.rs +++ b/06_uart_chainloader/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. diff --git a/06_uart_chainloader/src/synchronization.rs b/06_uart_chainloader/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/06_uart_chainloader/src/synchronization.rs +++ b/06_uart_chainloader/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/06_uart_chainloader/tests/chainboot_test.rb b/06_uart_chainloader/tests/chainboot_test.rb index 56099740..00de42a3 100644 --- a/06_uart_chainloader/tests/chainboot_test.rb +++ b/06_uart_chainloader/tests/chainboot_test.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2020-2022 Andre Richter +# Copyright (c) 2020-2023 Andre Richter require_relative '../../common/serial/minipush' require_relative '../../common/tests/boot_test' @@ -69,9 +69,9 @@ class ChainbootTest < BootTest end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Execution starts here -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- payload_path = ARGV.pop qemu_cmd = ARGV.join(' ') diff --git a/07_timestamps/.vscode/settings.json b/07_timestamps/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/07_timestamps/.vscode/settings.json +++ b/07_timestamps/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index b14b49bb..be8e7c13 100644 --- a/07_timestamps/Cargo.lock +++ b/07_timestamps/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,12 +15,12 @@ dependencies = [ name = "mingo" version = "0.7.0" dependencies = [ - "cortex-a", + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/07_timestamps/Cargo.toml b/07_timestamps/Cargo.toml index 970def3b..f4e4bcf6 100644 --- a/07_timestamps/Cargo.toml +++ b/07_timestamps/Cargo.toml @@ -23,8 +23,8 @@ path = "src/main.rs" [dependencies] # Optional dependencies -tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/07_timestamps/Makefile b/07_timestamps/Makefile index 3f6b230a..b13f0dfb 100644 --- a/07_timestamps/Makefile +++ b/07_timestamps/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -54,14 +55,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -84,7 +85,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -146,7 +146,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -204,7 +204,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -214,12 +213,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/07_timestamps/README.CN.md b/07_timestamps/README.CN.md new file mode 100644 index 00000000..1192996d --- /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 index 14bdc6bd..af44e8cc 100644 --- a/07_timestamps/README.md +++ b/07_timestamps/README.md @@ -19,6 +19,7 @@ Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now + __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | @@ -30,16 +31,16 @@ Minipush 1.0 [MP] ⏩ Pushing 12 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now -[ 0.140431] mingo version 0.7.0 -[ 0.140630] Booting on: Raspberry Pi 3 -[ 0.141085] Architectural timer resolution: 52 ns -[ 0.141660] Drivers loaded: -[ 0.141995] 1. BCM GPIO -[ 0.142353] 2. BCM PL011 UART -[W 0.142777] Spin duration smaller than architecturally supported, skipping -[ 0.143621] Spinning for 1 second -[ 1.144023] Spinning for 1 second -[ 2.144245] Spinning for 1 second +[ 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 @@ -62,7 +63,7 @@ Binary files 06_uart_chainloader/demo_payload_rpi4.img and 07_timestamps/demo_pa diff -uNr 06_uart_chainloader/Makefile 07_timestamps/Makefile --- 06_uart_chainloader/Makefile +++ 07_timestamps/Makefile -@@ -23,29 +23,27 @@ +@@ -24,29 +24,27 @@ QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) @@ -149,7 +150,7 @@ diff -uNr 06_uart_chainloader/Makefile 07_timestamps/Makefile ##------------------------------------------------------------------------------ ## Run clippy -@@ -245,8 +239,7 @@ +@@ -238,8 +232,7 @@ ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @@ -178,10 +179,10 @@ diff -uNr 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s 07_timestamps/src/_ar - movk \register, #:abs_g0_nc:\symbol -.endm - - .equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- -@@ -50,35 +39,23 @@ + // Public Code + //-------------------------------------------------------------------------------------------------- +@@ -48,35 +37,31 @@ // If execution reaches here, it is the boot core. // Initialize DRAM. @@ -219,6 +220,14 @@ diff -uNr 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s 07_timestamps/src/_ar - // 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 @@ -248,10 +257,10 @@ diff -uNr 06_uart_chainloader/src/_arch/aarch64/cpu.rs 07_timestamps/src/_arch/a 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,121 @@ +@@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! @@ -262,124 +271,165 @@ diff -uNr 06_uart_chainloader/src/_arch/aarch64/time.rs 07_timestamps/src/_arch/ +//! +//! crate::time::arch_time + -+use crate::{time, warn}; -+use core::time::Duration; -+use cortex_a::{asm::barrier, registers::*}; -+use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; ++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; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + -+impl GenericTimer { -+ #[inline(always)] -+ fn read_cntpct(&self) -> u64 { -+ // Prevent that the counter is read ahead of time due to out-of-order execution. -+ unsafe { barrier::isb(barrier::SY) }; -+ CNTPCT_EL0.get() -+ } ++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) } +} + -+//-------------------------------------------------------------------------------------------------- -+// Public Code -+//-------------------------------------------------------------------------------------------------- -+ -+/// Return a reference to the time manager. -+pub fn time_manager() -> &'static impl time::interface::TimeManager { -+ &TIME_MANAGER ++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(); ++ ++ // Div implementation for u64 cannot panic. ++ let secs = counter_value.0.div(frequency); + -+ fn uptime(&self) -> Duration { -+ let current_count: u64 = self.read_cntpct() * NS_PER_S; -+ let frq: u64 = CNTFRQ_EL0.get() as u64; ++ // 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::from_nanos(current_count / frq) ++ 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(); -+ let x = match frq.checked_mul(duration.as_nanos() as u64) { -+ #[allow(unused_imports)] -+ 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 -+ }; -+ -+ #[allow(unused_imports)] -+ 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. ++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 -@@ -143,25 +143,19 @@ +@@ -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, time::interface::TimeManager}; ++ use crate::time; + use core::time::Duration; - // Make an educated guess for a good delay value (Sequence described in the BCM2837 @@ -410,7 +460,7 @@ diff -uNr 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 07_times 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 -@@ -278,7 +278,7 @@ +@@ -275,7 +275,7 @@ } /// Retrieve a character. @@ -419,7 +469,7 @@ diff -uNr 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 07 // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. -@@ -293,7 +293,12 @@ +@@ -290,7 +290,12 @@ } // Read one character. @@ -433,7 +483,7 @@ diff -uNr 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 07 // Update statistics. self.chars_read += 1; -@@ -373,14 +378,14 @@ +@@ -376,14 +381,14 @@ impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner @@ -451,11 +501,33 @@ diff -uNr 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 07 {} } -diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/link.ld 07_timestamps/src/bsp/raspberrypi/link.ld ---- 06_uart_chainloader/src/bsp/raspberrypi/link.ld -+++ 07_timestamps/src/bsp/raspberrypi/link.ld +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-2022 Andre Richter + * Copyright (c) 2018-2023 Andre Richter */ +__rpi_phys_dram_start_addr = 0; @@ -481,7 +553,7 @@ diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/link.ld 07_timestamps/src/bsp/ .text : { KEEP(*(.text._start)) -@@ -61,10 +61,6 @@ +@@ -60,10 +60,6 @@ ***********************************************************************************************/ .data : { *(.data*) } :segment_data @@ -496,19 +568,14 @@ diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/link.ld 07_timestamps/src/bsp/ 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,10 +11,9 @@ +@@ -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; -+ pub const GPIO_OFFSET: usize = 0x0020_0000; -+ pub const UART_OFFSET: usize = 0x0020_1000; - - /// Physical devices. - #[cfg(feature = "bsp_rpi3")] + 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; } @@ -535,10 +602,54 @@ diff -uNr 06_uart_chainloader/src/cpu.rs 07_timestamps/src/cpu.rs -#[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 -@@ -118,6 +118,7 @@ +@@ -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; @@ -546,7 +657,7 @@ diff -uNr 06_uart_chainloader/src/main.rs 07_timestamps/src/main.rs /// Early init code. /// -@@ -140,56 +141,38 @@ +@@ -142,55 +146,30 @@ kernel_main() } @@ -559,12 +670,8 @@ diff -uNr 06_uart_chainloader/src/main.rs 07_timestamps/src/main.rs - /// 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; - +- use console::console; +- - println!("{}", MINILOAD_LOGO); - println!("{:^37}", bsp::board_name()); - println!(); @@ -577,26 +684,8 @@ diff -uNr 06_uart_chainloader/src/main.rs 07_timestamps/src/main.rs - // Notify `Minipush` to send the binary. - for _ in 0..3 { - console().write_char(3 as char); -+ 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:"); -+ for (i, driver) in bsp::driver::driver_manager() -+ .all_device_drivers() -+ .iter() -+ .enumerate() -+ { -+ info!(" {}. {}", i + 1, driver.compatible()); - } +- } ++ use core::time::Duration; - // Read the binary's size. - let mut size: u32 = u32::from(console().read_char() as u8); @@ -614,10 +703,29 @@ diff -uNr 06_uart_chainloader/src/main.rs 07_timestamps/src/main.rs - 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(); - @@ -626,21 +734,12 @@ diff -uNr 06_uart_chainloader/src/main.rs 07_timestamps/src/main.rs - - // Jump to loaded kernel! - kernel() -+ loop { -+ info!("Spinning for 1 second"); -+ time::time_manager().spin_for(Duration::from_secs(1)); -+ } } 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 -@@ -58,18 +58,23 @@ - - #[panic_handler] - fn panic(info: &PanicInfo) -> ! { -+ use crate::time::interface::TimeManager; -+ +@@ -45,15 +45,18 @@ // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -650,7 +749,7 @@ diff -uNr 06_uart_chainloader/src/panic_wait.rs 07_timestamps/src/panic_wait.rs _ => ("???", 0, 0), }; - panic_println!( + println!( - "Kernel panic!\n\n\ + "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ @@ -664,7 +763,7 @@ diff -uNr 06_uart_chainloader/src/panic_wait.rs 07_timestamps/src/panic_wait.rs diff -uNr 06_uart_chainloader/src/print.rs 07_timestamps/src/print.rs --- 06_uart_chainloader/src/print.rs +++ 07_timestamps/src/print.rs -@@ -36,3 +36,59 @@ +@@ -34,3 +34,51 @@ $crate::print::_print(format_args_nl!($($arg)*)); }) } @@ -673,8 +772,6 @@ diff -uNr 06_uart_chainloader/src/print.rs 07_timestamps/src/print.rs +#[macro_export] +macro_rules! info { + ($string:expr) => ({ -+ use $crate::time::interface::TimeManager; -+ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( @@ -684,8 +781,6 @@ diff -uNr 06_uart_chainloader/src/print.rs 07_timestamps/src/print.rs + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ -+ use $crate::time::interface::TimeManager; -+ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( @@ -701,8 +796,6 @@ diff -uNr 06_uart_chainloader/src/print.rs 07_timestamps/src/print.rs +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ -+ use $crate::time::interface::TimeManager; -+ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( @@ -712,8 +805,6 @@ diff -uNr 06_uart_chainloader/src/print.rs 07_timestamps/src/print.rs + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ -+ use $crate::time::interface::TimeManager; -+ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( @@ -728,10 +819,10 @@ diff -uNr 06_uart_chainloader/src/print.rs 07_timestamps/src/print.rs 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,37 @@ +@@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2020-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + @@ -739,31 +830,51 @@ diff -uNr 06_uart_chainloader/src/time.rs 07_timestamps/src/time.rs +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + ++use core::time::Duration; ++ ++//-------------------------------------------------------------------------------------------------- ++// Public Definitions ++//-------------------------------------------------------------------------------------------------- ++ ++/// Provides time management functions. ++pub struct TimeManager; ++ +//-------------------------------------------------------------------------------------------------- -+// Architectural Public Reexports ++// Global instances +//-------------------------------------------------------------------------------------------------- -+pub use arch_time::time_manager; ++ ++static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- -+// Public Definitions ++// Public Code +//-------------------------------------------------------------------------------------------------- + -+/// Timekeeping interfaces. -+pub mod interface { -+ use core::time::Duration; ++/// Return a reference to the global TimeManager. ++pub fn time_manager() -> &'static TimeManager { ++ &TIME_MANAGER ++} + -+ /// Time management functions. -+ pub trait TimeManager { -+ /// The timer's resolution. -+ fn resolution(&self) -> Duration; ++impl TimeManager { ++ /// Create an instance. ++ pub const fn new() -> Self { ++ Self ++ } + -+ /// The uptime since power-on of the device. -+ /// -+ /// This includes time consumed by firmware and bootloaders. -+ fn uptime(&self) -> Duration; ++ /// 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. -+ fn spin_for(&self, duration: Duration); ++ /// Spin for a given duration. ++ pub fn spin_for(&self, duration: Duration) { ++ arch_time::spin_for(duration) + } +} @@ -783,7 +894,7 @@ diff -uNr 06_uart_chainloader/tests/chainboot_test.rb 07_timestamps/tests/chainb - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# --# Copyright (c) 2020-2022 Andre Richter +-# Copyright (c) 2020-2023 Andre Richter - -require_relative '../../common/serial/minipush' -require_relative '../../common/tests/boot_test' diff --git a/07_timestamps/src/_arch/aarch64/cpu.rs b/07_timestamps/src/_arch/aarch64/cpu.rs index 4414ac6a..602c9789 100644 --- a/07_timestamps/src/_arch/aarch64/cpu.rs +++ b/07_timestamps/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/07_timestamps/src/_arch/aarch64/cpu/boot.rs b/07_timestamps/src/_arch/aarch64/cpu/boot.rs index 2f9654c7..2a6c4649 100644 --- a/07_timestamps/src/_arch/aarch64/cpu/boot.rs +++ b/07_timestamps/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,8 +11,13 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/07_timestamps/src/_arch/aarch64/cpu/boot.s b/07_timestamps/src/_arch/aarch64/cpu/boot.s index 7d445a93..0b801b4b 100644 --- a/07_timestamps/src/_arch/aarch64/cpu/boot.s +++ b/07_timestamps/src/_arch/aarch64/cpu/boot.s @@ -18,8 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -30,10 +28,10 @@ //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. - mrs x1, MPIDR_EL1 - and x1, x1, _core_id_mask - ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs - cmp x1, x2 + 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. @@ -54,6 +52,14 @@ _start: 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 diff --git a/07_timestamps/src/_arch/aarch64/time.rs b/07_timestamps/src/_arch/aarch64/time.rs index c814219c..ee1c3ef7 100644 --- a/07_timestamps/src/_arch/aarch64/time.rs +++ b/07_timestamps/src/_arch/aarch64/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural timer primitives. //! @@ -11,111 +11,152 @@ //! //! crate::time::arch_time -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; +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; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } +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) } } -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER +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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; + // 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(); - let x = match frq.checked_mul(duration.as_nanos() as u64) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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. +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 index 824787f6..246973bc 100644 --- a/07_timestamps/src/bsp.rs +++ b/07_timestamps/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/07_timestamps/src/bsp/device_driver.rs b/07_timestamps/src/bsp/device_driver.rs index 6e9bf8f3..64049a4c 100644 --- a/07_timestamps/src/bsp/device_driver.rs +++ b/07_timestamps/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/07_timestamps/src/bsp/device_driver/bcm.rs b/07_timestamps/src/bsp/device_driver/bcm.rs index b4b7906e..1c343d1d 100644 --- a/07_timestamps/src/bsp/device_driver/bcm.rs +++ b/07_timestamps/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. diff --git a/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs index dbb4beaa..8e57dfed 100644 --- a/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ b/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -143,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. @@ -189,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -214,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/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs index 878ea567..d92612ea 100644 --- a/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ b/07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -326,7 +323,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -346,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> { @@ -364,7 +367,7 @@ 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)) } @@ -400,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/07_timestamps/src/bsp/device_driver/common.rs b/07_timestamps/src/bsp/device_driver/common.rs index fd9e988e..dfe7d8ef 100644 --- a/07_timestamps/src/bsp/device_driver/common.rs +++ b/07_timestamps/src/bsp/device_driver/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/07_timestamps/src/bsp/raspberrypi.rs b/07_timestamps/src/bsp/raspberrypi.rs index 22edb4fa..3ea864dc 100644 --- a/07_timestamps/src/bsp/raspberrypi.rs +++ b/07_timestamps/src/bsp/raspberrypi.rs @@ -1,25 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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) }; - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- diff --git a/07_timestamps/src/bsp/raspberrypi/console.rs b/07_timestamps/src/bsp/raspberrypi/console.rs deleted file mode 100644 index a247032f..00000000 --- a/07_timestamps/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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_timestamps/src/bsp/raspberrypi/cpu.rs b/07_timestamps/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/07_timestamps/src/bsp/raspberrypi/cpu.rs +++ b/07_timestamps/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. diff --git a/07_timestamps/src/bsp/raspberrypi/driver.rs b/07_timestamps/src/bsp/raspberrypi/driver.rs index b5538baa..7716fe3f 100644 --- a/07_timestamps/src/bsp/raspberrypi/driver.rs +++ b/07_timestamps/src/bsp/raspberrypi/driver.rs @@ -1,49 +1,82 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. +/// +/// # 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 00000000..f6c18843 --- /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/link.ld b/07_timestamps/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 007afd4a..00000000 --- a/07_timestamps/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,72 +0,0 @@ -/* 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 - .got : ALIGN(8) { *(.got) } :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 -} diff --git a/07_timestamps/src/bsp/raspberrypi/memory.rs b/07_timestamps/src/bsp/raspberrypi/memory.rs index 27be8590..cdca14b8 100644 --- a/07_timestamps/src/bsp/raspberrypi/memory.rs +++ b/07_timestamps/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. diff --git a/07_timestamps/src/console.rs b/07_timestamps/src/console.rs index e49e241f..a83f86fe 100644 --- a/07_timestamps/src/console.rs +++ b/07_timestamps/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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/07_timestamps/src/console/null_console.rs b/07_timestamps/src/console/null_console.rs new file mode 100644 index 00000000..e92a022b --- /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 index 62503fb4..67ab79c0 100644 --- a/07_timestamps/src/cpu.rs +++ b/07_timestamps/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/07_timestamps/src/cpu/boot.rs b/07_timestamps/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/07_timestamps/src/cpu/boot.rs +++ b/07_timestamps/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/07_timestamps/src/driver.rs b/07_timestamps/src/driver.rs index 2fcc7562..050e7022 100644 --- a/07_timestamps/src/driver.rs +++ b/07_timestamps/src/driver.rs @@ -1,9 +1,25 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// 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 //-------------------------------------------------------------------------------------------------- @@ -24,21 +40,128 @@ 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>; + +/// 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()), + } + } - /// Device driver management functions. + /// 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 + ); + } + } + }); + } + + /// 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 index 3d4ace4f..b094dacc 100644 --- a/07_timestamps/src/main.rs +++ b/07_timestamps/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -105,9 +107,13 @@ //! 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] @@ -127,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. @@ -144,8 +149,6 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; info!( "{} version {}", @@ -160,13 +163,7 @@ fn kernel_main() -> ! { ); info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); // Test a failing timer case. time::time_manager().spin_for(Duration::from_nanos(1)); diff --git a/07_timestamps/src/panic_wait.rs b/07_timestamps/src/panic_wait.rs index f851e0d8..5776aca8 100644 --- a/07_timestamps/src/panic_wait.rs +++ b/07_timestamps/src/panic_wait.rs @@ -1,32 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -58,8 +42,6 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -69,7 +51,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/07_timestamps/src/print.rs b/07_timestamps/src/print.rs index 9ec13a28..8e303046 100644 --- a/07_timestamps/src/print.rs +++ b/07_timestamps/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/07_timestamps/src/synchronization.rs b/07_timestamps/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/07_timestamps/src/synchronization.rs +++ b/07_timestamps/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/07_timestamps/src/time.rs b/07_timestamps/src/time.rs index 6d92b196..a9d50120 100644 --- a/07_timestamps/src/time.rs +++ b/07_timestamps/src/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Timer primitives. @@ -8,30 +8,50 @@ #[path = "_arch/aarch64/time.rs"] mod arch_time; +use core::time::Duration; + //-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports +// Public Definitions //-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; + +/// Provides time management functions. +pub struct TimeManager; //-------------------------------------------------------------------------------------------------- -// Public Definitions +// Global instances //-------------------------------------------------------------------------------------------------- -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; +static TIME_MANAGER: TimeManager = TimeManager::new(); - /// Time management functions. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; +/// 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. - fn spin_for(&self, duration: Duration); + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) } } diff --git a/08_hw_debug_JTAG/.vscode/settings.json b/08_hw_debug_JTAG/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/08_hw_debug_JTAG/.vscode/settings.json +++ b/08_hw_debug_JTAG/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index ef4ed866..9020b4f9 100644 --- a/08_hw_debug_JTAG/Cargo.lock +++ b/08_hw_debug_JTAG/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,12 +15,12 @@ dependencies = [ name = "mingo" version = "0.8.0" dependencies = [ - "cortex-a", + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/08_hw_debug_JTAG/Cargo.toml b/08_hw_debug_JTAG/Cargo.toml index 638d4de1..e310c371 100644 --- a/08_hw_debug_JTAG/Cargo.toml +++ b/08_hw_debug_JTAG/Cargo.toml @@ -23,8 +23,8 @@ path = "src/main.rs" [dependencies] # Optional dependencies -tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/08_hw_debug_JTAG/Makefile b/08_hw_debug_JTAG/Makefile index e3db66a9..9549f092 100644 --- a/08_hw_debug_JTAG/Makefile +++ b/08_hw_debug_JTAG/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -58,14 +59,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -88,7 +89,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -157,7 +157,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -215,7 +215,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -225,12 +224,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/08_hw_debug_JTAG/README.CN.md b/08_hw_debug_JTAG/README.CN.md new file mode 100644 index 00000000..b7703210 --- /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 index 902ca6e4..14928253 100644 --- a/08_hw_debug_JTAG/README.md +++ b/08_hw_debug_JTAG/README.md @@ -320,7 +320,7 @@ diff -uNr 07_timestamps/Cargo.toml 08_hw_debug_JTAG/Cargo.toml diff -uNr 07_timestamps/Makefile 08_hw_debug_JTAG/Makefile --- 07_timestamps/Makefile +++ 08_hw_debug_JTAG/Makefile -@@ -31,6 +31,8 @@ +@@ -32,6 +32,8 @@ OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf @@ -329,7 +329,7 @@ diff -uNr 07_timestamps/Makefile 08_hw_debug_JTAG/Makefile LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) -@@ -42,6 +44,8 @@ +@@ -43,6 +45,8 @@ OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf @@ -364,7 +364,7 @@ diff -uNr 07_timestamps/Makefile 08_hw_debug_JTAG/Makefile endif -@@ -222,6 +233,35 @@ +@@ -215,6 +226,35 @@ @@ -401,4 +401,26 @@ diff -uNr 07_timestamps/Makefile 08_hw_debug_JTAG/Makefile ## 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/src/_arch/aarch64/cpu.rs b/08_hw_debug_JTAG/src/_arch/aarch64/cpu.rs index 4414ac6a..602c9789 100644 --- a/08_hw_debug_JTAG/src/_arch/aarch64/cpu.rs +++ b/08_hw_debug_JTAG/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs b/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs index 2f9654c7..2a6c4649 100644 --- a/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs +++ b/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,8 +11,13 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s b/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s index 7d445a93..0b801b4b 100644 --- a/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s +++ b/08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s @@ -18,8 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -30,10 +28,10 @@ //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. - mrs x1, MPIDR_EL1 - and x1, x1, _core_id_mask - ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs - cmp x1, x2 + 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. @@ -54,6 +52,14 @@ _start: 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 diff --git a/08_hw_debug_JTAG/src/_arch/aarch64/time.rs b/08_hw_debug_JTAG/src/_arch/aarch64/time.rs index c814219c..ee1c3ef7 100644 --- a/08_hw_debug_JTAG/src/_arch/aarch64/time.rs +++ b/08_hw_debug_JTAG/src/_arch/aarch64/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural timer primitives. //! @@ -11,111 +11,152 @@ //! //! crate::time::arch_time -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; +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; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } +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) } } -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER +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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; + // 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(); - let x = match frq.checked_mul(duration.as_nanos() as u64) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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. +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 index 824787f6..246973bc 100644 --- a/08_hw_debug_JTAG/src/bsp.rs +++ b/08_hw_debug_JTAG/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/08_hw_debug_JTAG/src/bsp/device_driver.rs b/08_hw_debug_JTAG/src/bsp/device_driver.rs index 6e9bf8f3..64049a4c 100644 --- a/08_hw_debug_JTAG/src/bsp/device_driver.rs +++ b/08_hw_debug_JTAG/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/08_hw_debug_JTAG/src/bsp/device_driver/bcm.rs b/08_hw_debug_JTAG/src/bsp/device_driver/bcm.rs index b4b7906e..1c343d1d 100644 --- a/08_hw_debug_JTAG/src/bsp/device_driver/bcm.rs +++ b/08_hw_debug_JTAG/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. 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 index dbb4beaa..8e57dfed 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -143,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. @@ -189,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -214,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/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 index 878ea567..d92612ea 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -326,7 +323,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -346,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> { @@ -364,7 +367,7 @@ 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)) } @@ -400,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/08_hw_debug_JTAG/src/bsp/device_driver/common.rs b/08_hw_debug_JTAG/src/bsp/device_driver/common.rs index fd9e988e..dfe7d8ef 100644 --- a/08_hw_debug_JTAG/src/bsp/device_driver/common.rs +++ b/08_hw_debug_JTAG/src/bsp/device_driver/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi.rs index 22edb4fa..3ea864dc 100644 --- a/08_hw_debug_JTAG/src/bsp/raspberrypi.rs +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi.rs @@ -1,25 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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) }; - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi/console.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi/console.rs deleted file mode 100644 index a247032f..00000000 --- a/08_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-2022 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_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/08_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs index b5538baa..2a80ee2c 100644 --- a/08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs @@ -1,49 +1,71 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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/08_hw_debug_JTAG/src/bsp/raspberrypi/kernel.ld b/08_hw_debug_JTAG/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 00000000..f6c18843 --- /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/link.ld b/08_hw_debug_JTAG/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 007afd4a..00000000 --- a/08_hw_debug_JTAG/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,72 +0,0 @@ -/* 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 - .got : ALIGN(8) { *(.got) } :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 -} diff --git a/08_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs b/08_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs index 27be8590..cdca14b8 100644 --- a/08_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs +++ b/08_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. diff --git a/08_hw_debug_JTAG/src/console.rs b/08_hw_debug_JTAG/src/console.rs index e49e241f..a83f86fe 100644 --- a/08_hw_debug_JTAG/src/console.rs +++ b/08_hw_debug_JTAG/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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/08_hw_debug_JTAG/src/console/null_console.rs b/08_hw_debug_JTAG/src/console/null_console.rs new file mode 100644 index 00000000..e92a022b --- /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 index 62503fb4..67ab79c0 100644 --- a/08_hw_debug_JTAG/src/cpu.rs +++ b/08_hw_debug_JTAG/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/08_hw_debug_JTAG/src/cpu/boot.rs b/08_hw_debug_JTAG/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/08_hw_debug_JTAG/src/cpu/boot.rs +++ b/08_hw_debug_JTAG/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/08_hw_debug_JTAG/src/driver.rs b/08_hw_debug_JTAG/src/driver.rs index 2fcc7562..050e7022 100644 --- a/08_hw_debug_JTAG/src/driver.rs +++ b/08_hw_debug_JTAG/src/driver.rs @@ -1,9 +1,25 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// 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 //-------------------------------------------------------------------------------------------------- @@ -24,21 +40,128 @@ 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>; + +/// 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()), + } + } - /// Device driver management functions. + /// 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 + ); + } + } + }); + } + + /// 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 index 3d4ace4f..b094dacc 100644 --- a/08_hw_debug_JTAG/src/main.rs +++ b/08_hw_debug_JTAG/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -105,9 +107,13 @@ //! 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] @@ -127,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. @@ -144,8 +149,6 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; info!( "{} version {}", @@ -160,13 +163,7 @@ fn kernel_main() -> ! { ); info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); // Test a failing timer case. time::time_manager().spin_for(Duration::from_nanos(1)); diff --git a/08_hw_debug_JTAG/src/panic_wait.rs b/08_hw_debug_JTAG/src/panic_wait.rs index f851e0d8..5776aca8 100644 --- a/08_hw_debug_JTAG/src/panic_wait.rs +++ b/08_hw_debug_JTAG/src/panic_wait.rs @@ -1,32 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -58,8 +42,6 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -69,7 +51,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/08_hw_debug_JTAG/src/print.rs b/08_hw_debug_JTAG/src/print.rs index 9ec13a28..8e303046 100644 --- a/08_hw_debug_JTAG/src/print.rs +++ b/08_hw_debug_JTAG/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/08_hw_debug_JTAG/src/synchronization.rs b/08_hw_debug_JTAG/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/08_hw_debug_JTAG/src/synchronization.rs +++ b/08_hw_debug_JTAG/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/08_hw_debug_JTAG/src/time.rs b/08_hw_debug_JTAG/src/time.rs index 6d92b196..a9d50120 100644 --- a/08_hw_debug_JTAG/src/time.rs +++ b/08_hw_debug_JTAG/src/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Timer primitives. @@ -8,30 +8,50 @@ #[path = "_arch/aarch64/time.rs"] mod arch_time; +use core::time::Duration; + //-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports +// Public Definitions //-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; + +/// Provides time management functions. +pub struct TimeManager; //-------------------------------------------------------------------------------------------------- -// Public Definitions +// Global instances //-------------------------------------------------------------------------------------------------- -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; +static TIME_MANAGER: TimeManager = TimeManager::new(); - /// Time management functions. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; +/// 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. - fn spin_for(&self, duration: Duration); + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) } } diff --git a/09_privilege_level/.vscode/settings.json b/09_privilege_level/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/09_privilege_level/.vscode/settings.json +++ b/09_privilege_level/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index 49e377d2..12b21042 100644 --- a/09_privilege_level/Cargo.lock +++ b/09_privilege_level/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,12 +15,12 @@ dependencies = [ name = "mingo" version = "0.9.0" dependencies = [ - "cortex-a", + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/09_privilege_level/Cargo.toml b/09_privilege_level/Cargo.toml index dccb5622..480508b5 100644 --- a/09_privilege_level/Cargo.toml +++ b/09_privilege_level/Cargo.toml @@ -23,8 +23,8 @@ path = "src/main.rs" [dependencies] # Optional dependencies -tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/09_privilege_level/Makefile b/09_privilege_level/Makefile index e3db66a9..9549f092 100644 --- a/09_privilege_level/Makefile +++ b/09_privilege_level/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -58,14 +59,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -88,7 +89,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -157,7 +157,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -215,7 +215,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -225,12 +224,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/09_privilege_level/README.CN.md b/09_privilege_level/README.CN.md new file mode 100644 index 00000000..80773a69 --- /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 index 729634ac..ca2b920f 100644 --- a/09_privilege_level/README.md +++ b/09_privilege_level/README.md @@ -34,7 +34,7 @@ architectures, please have a look at the following links: 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 forARMv8-A]: http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf +[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 @@ -50,8 +50,8 @@ core should it not be in `EL2`. ``` // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL -cmp x0, _EL2 -b.ne 1f +cmp x0, {CONST_CURRENTEL_EL2} +b.ne .L_parking_loop ``` Afterwards, we continue with preparing the `EL2` -> `EL1` transition by calling @@ -75,7 +75,7 @@ We are already using them since [tutorial 07](../07_timestamps/), so of course w 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/5.1.2/src/cortex_a/regs/cnthctl_el2.rs.html +[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. @@ -88,7 +88,7 @@ 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/cortex-a/5.1.2/src/cortex_a/regs/hcr_el2.rs.html +[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. @@ -100,7 +100,7 @@ HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); 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/5.1.2/src/cortex_a/asm.rs.html#87-96 +[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 @@ -109,8 +109,8 @@ 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/cortex-a/5.1.2/src/cortex_a/regs/spsr_el2.rs.html -[Exception Link Register - EL2]: https://docs.rs/cortex-a/5.1.2/src/cortex_a/regs/elr_el2.rs.html +[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. @@ -166,6 +166,7 @@ Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now + __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | @@ -177,20 +178,20 @@ Minipush 1.0 [MP] ⏩ Pushing 14 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now -[ 0.165757] mingo version 0.9.0 -[ 0.165957] Booting on: Raspberry Pi 3 -[ 0.166412] Current privilege level: EL1 -[ 0.166888] Exception handling state: -[ 0.167333] Debug: Masked -[ 0.167723] SError: Masked -[ 0.168112] IRQ: Masked -[ 0.168502] FIQ: Masked -[ 0.168893] Architectural timer resolution: 52 ns -[ 0.169467] Drivers loaded: -[ 0.169803] 1. BCM GPIO -[ 0.170160] 2. BCM PL011 UART -[ 0.170583] Timer test, spinning for 1 second -[ 1.171115] Echoing input 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 @@ -211,19 +212,22 @@ diff -uNr 08_hw_debug_JTAG/Cargo.toml 09_privilege_level/Cargo.toml 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,8 +11,53 @@ +@@ -11,22 +11,73 @@ //! //! crate::cpu::boot::arch_boot -+use core::arch::global_asm; -+use cortex_a::{asm, registers::*}; ++use aarch64_cpu::{asm, registers::*}; + use core::arch::global_asm; +use tock_registers::interfaces::Writeable; -+ + // Assembly counterpart to this file. --core::arch::global_asm!(include_str!("boot.s")); -+global_asm!(include_str!("boot.s")); -+ -+//-------------------------------------------------------------------------------------------------- + global_asm!( + include_str!("boot.s"), ++ CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 + ); + + //-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + @@ -263,10 +267,11 @@ diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs 09_privilege_level/src/ + // 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 -@@ -21,7 +66,14 @@ + //-------------------------------------------------------------------------------------------------- + /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. @@ -287,27 +292,28 @@ diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs 09_privilege_level/src/ 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 -@@ -18,6 +18,7 @@ - add \register, \register, #:lo12:\symbol - .endm - -+.equ _EL2, 0x8 - .equ _core_id_mask, 0b11 - - //-------------------------------------------------------------------------------------------------- -@@ -29,6 +30,11 @@ +@@ -27,11 +27,16 @@ // fn _start() //------------------------------------------------------------------------------ _start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL -+ cmp x0, _EL2 ++ 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, _core_id_mask -@@ -50,11 +56,11 @@ +- 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: @@ -316,6 +322,10 @@ diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s 09_privilege_level/src/_ 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 @@ -328,7 +338,7 @@ diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/exception/asynchronous.rs 09_privil @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! @@ -339,7 +349,7 @@ diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/exception/asynchronous.rs 09_privil +//! +//! crate::exception::asynchronous::arch_asynchronous + -+use cortex_a::registers::*; ++use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- @@ -415,7 +425,7 @@ diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/exception.rs 09_privilege_level/src @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! @@ -426,7 +436,7 @@ diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/exception.rs 09_privilege_level/src +//! +//! crate::exception::arch_exception + -+use cortex_a::registers::*; ++use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- @@ -451,7 +461,7 @@ diff -uNr 08_hw_debug_JTAG/src/exception/asynchronous.rs 09_privilege_level/src/ @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2020-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + @@ -470,7 +480,7 @@ diff -uNr 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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + @@ -491,7 +501,7 @@ diff -uNr 08_hw_debug_JTAG/src/exception.rs 09_privilege_level/src/exception.rs + +/// Kernel privilege levels. +#[allow(missing_docs)] -+#[derive(PartialEq)] ++#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, @@ -502,7 +512,7 @@ diff -uNr 08_hw_debug_JTAG/src/exception.rs 09_privilege_level/src/exception.rs 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 -@@ -115,6 +115,7 @@ +@@ -121,6 +121,7 @@ mod console; mod cpu; mod driver; @@ -510,16 +520,15 @@ diff -uNr 08_hw_debug_JTAG/src/main.rs 09_privilege_level/src/main.rs mod panic_wait; mod print; mod synchronization; -@@ -143,6 +144,8 @@ +@@ -148,6 +149,7 @@ /// The main function running after the early init. fn kernel_main() -> ! { -+ use bsp::console::console; -+ use console::interface::All; ++ use console::console; use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; -@@ -154,6 +157,12 @@ + + info!( +@@ -157,6 +159,12 @@ ); info!("Booting on: {}", bsp::board_name()); @@ -532,9 +541,9 @@ diff -uNr 08_hw_debug_JTAG/src/main.rs 09_privilege_level/src/main.rs info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() -@@ -168,11 +177,15 @@ - info!(" {}. {}", i + 1, driver.compatible()); - } +@@ -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)); @@ -548,8 +557,8 @@ diff -uNr 08_hw_debug_JTAG/src/main.rs 09_privilege_level/src/main.rs 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); ++ let c = console().read_char(); ++ console().write_char(c); } } diff --git a/09_privilege_level/src/_arch/aarch64/cpu.rs b/09_privilege_level/src/_arch/aarch64/cpu.rs index 4414ac6a..602c9789 100644 --- a/09_privilege_level/src/_arch/aarch64/cpu.rs +++ b/09_privilege_level/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/09_privilege_level/src/_arch/aarch64/cpu/boot.rs b/09_privilege_level/src/_arch/aarch64/cpu/boot.rs index f677c9c4..c80f3ebb 100644 --- a/09_privilege_level/src/_arch/aarch64/cpu/boot.rs +++ b/09_privilege_level/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,12 +11,16 @@ //! //! crate::cpu::boot::arch_boot +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; -use cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Private Code diff --git a/09_privilege_level/src/_arch/aarch64/cpu/boot.s b/09_privilege_level/src/_arch/aarch64/cpu/boot.s index 28b35087..f6df2123 100644 --- a/09_privilege_level/src/_arch/aarch64/cpu/boot.s +++ b/09_privilege_level/src/_arch/aarch64/cpu/boot.s @@ -18,9 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _EL2, 0x8 -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -32,12 +29,12 @@ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL - cmp x0, _EL2 + 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, _core_id_mask + 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 @@ -60,6 +57,14 @@ _start: 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 diff --git a/09_privilege_level/src/_arch/aarch64/exception.rs b/09_privilege_level/src/_arch/aarch64/exception.rs index c8eac4f0..1051af6a 100644 --- a/09_privilege_level/src/_arch/aarch64/exception.rs +++ b/09_privilege_level/src/_arch/aarch64/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! @@ -11,7 +11,7 @@ //! //! crate::exception::arch_exception -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- diff --git a/09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs b/09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs index e3e3672e..65fcad25 100644 --- a/09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs +++ b/09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! @@ -11,7 +11,7 @@ //! //! crate::exception::asynchronous::arch_asynchronous -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- diff --git a/09_privilege_level/src/_arch/aarch64/time.rs b/09_privilege_level/src/_arch/aarch64/time.rs index c814219c..ee1c3ef7 100644 --- a/09_privilege_level/src/_arch/aarch64/time.rs +++ b/09_privilege_level/src/_arch/aarch64/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural timer primitives. //! @@ -11,111 +11,152 @@ //! //! crate::time::arch_time -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; +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; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } +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) } } -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER +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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; + // 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(); - let x = match frq.checked_mul(duration.as_nanos() as u64) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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. +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 index 824787f6..246973bc 100644 --- a/09_privilege_level/src/bsp.rs +++ b/09_privilege_level/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/09_privilege_level/src/bsp/device_driver.rs b/09_privilege_level/src/bsp/device_driver.rs index 6e9bf8f3..64049a4c 100644 --- a/09_privilege_level/src/bsp/device_driver.rs +++ b/09_privilege_level/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/09_privilege_level/src/bsp/device_driver/bcm.rs b/09_privilege_level/src/bsp/device_driver/bcm.rs index b4b7906e..1c343d1d 100644 --- a/09_privilege_level/src/bsp/device_driver/bcm.rs +++ b/09_privilege_level/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. 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 index dbb4beaa..8e57dfed 100644 --- a/09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ b/09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -143,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. @@ -189,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -214,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/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 index 878ea567..d92612ea 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -326,7 +323,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -346,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> { @@ -364,7 +367,7 @@ 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)) } @@ -400,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/09_privilege_level/src/bsp/device_driver/common.rs b/09_privilege_level/src/bsp/device_driver/common.rs index fd9e988e..dfe7d8ef 100644 --- a/09_privilege_level/src/bsp/device_driver/common.rs +++ b/09_privilege_level/src/bsp/device_driver/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/09_privilege_level/src/bsp/raspberrypi.rs b/09_privilege_level/src/bsp/raspberrypi.rs index 22edb4fa..3ea864dc 100644 --- a/09_privilege_level/src/bsp/raspberrypi.rs +++ b/09_privilege_level/src/bsp/raspberrypi.rs @@ -1,25 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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) }; - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- diff --git a/09_privilege_level/src/bsp/raspberrypi/console.rs b/09_privilege_level/src/bsp/raspberrypi/console.rs deleted file mode 100644 index a247032f..00000000 --- a/09_privilege_level/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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_privilege_level/src/bsp/raspberrypi/cpu.rs b/09_privilege_level/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/09_privilege_level/src/bsp/raspberrypi/cpu.rs +++ b/09_privilege_level/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. diff --git a/09_privilege_level/src/bsp/raspberrypi/driver.rs b/09_privilege_level/src/bsp/raspberrypi/driver.rs index b5538baa..2a80ee2c 100644 --- a/09_privilege_level/src/bsp/raspberrypi/driver.rs +++ b/09_privilege_level/src/bsp/raspberrypi/driver.rs @@ -1,49 +1,71 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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/09_privilege_level/src/bsp/raspberrypi/kernel.ld b/09_privilege_level/src/bsp/raspberrypi/kernel.ld new file mode 100644 index 00000000..f6c18843 --- /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/link.ld b/09_privilege_level/src/bsp/raspberrypi/link.ld deleted file mode 100644 index 007afd4a..00000000 --- a/09_privilege_level/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,72 +0,0 @@ -/* 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 - .got : ALIGN(8) { *(.got) } :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 -} diff --git a/09_privilege_level/src/bsp/raspberrypi/memory.rs b/09_privilege_level/src/bsp/raspberrypi/memory.rs index 27be8590..cdca14b8 100644 --- a/09_privilege_level/src/bsp/raspberrypi/memory.rs +++ b/09_privilege_level/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. diff --git a/09_privilege_level/src/console.rs b/09_privilege_level/src/console.rs index e49e241f..a83f86fe 100644 --- a/09_privilege_level/src/console.rs +++ b/09_privilege_level/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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/09_privilege_level/src/console/null_console.rs b/09_privilege_level/src/console/null_console.rs new file mode 100644 index 00000000..e92a022b --- /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 index 62503fb4..67ab79c0 100644 --- a/09_privilege_level/src/cpu.rs +++ b/09_privilege_level/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/09_privilege_level/src/cpu/boot.rs b/09_privilege_level/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/09_privilege_level/src/cpu/boot.rs +++ b/09_privilege_level/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/09_privilege_level/src/driver.rs b/09_privilege_level/src/driver.rs index 2fcc7562..050e7022 100644 --- a/09_privilege_level/src/driver.rs +++ b/09_privilege_level/src/driver.rs @@ -1,9 +1,25 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// 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 //-------------------------------------------------------------------------------------------------- @@ -24,21 +40,128 @@ 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>; + +/// 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()), + } + } - /// Device driver management functions. + /// 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 + ); + } + } + }); + } + + /// 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 index b80248f7..45760391 100644 --- a/09_privilege_level/src/exception.rs +++ b/09_privilege_level/src/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. @@ -21,7 +21,7 @@ pub use arch_exception::current_privilege_level; /// Kernel privilege levels. #[allow(missing_docs)] -#[derive(PartialEq)] +#[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, diff --git a/09_privilege_level/src/exception/asynchronous.rs b/09_privilege_level/src/exception/asynchronous.rs index bad85779..fd059326 100644 --- a/09_privilege_level/src/exception/asynchronous.rs +++ b/09_privilege_level/src/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Asynchronous exception handling. diff --git a/09_privilege_level/src/main.rs b/09_privilege_level/src/main.rs index b4449734..cc0e1dfd 100644 --- a/09_privilege_level/src/main.rs +++ b/09_privilege_level/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -105,9 +107,13 @@ //! 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] @@ -128,14 +134,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. @@ -144,11 +149,8 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; + use console::console; use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; info!( "{} version {}", @@ -169,13 +171,7 @@ fn kernel_main() -> ! { ); info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); @@ -185,7 +181,7 @@ fn kernel_main() -> ! { // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); + 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 index f851e0d8..5776aca8 100644 --- a/09_privilege_level/src/panic_wait.rs +++ b/09_privilege_level/src/panic_wait.rs @@ -1,32 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -58,8 +42,6 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -69,7 +51,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/09_privilege_level/src/print.rs b/09_privilege_level/src/print.rs index 9ec13a28..8e303046 100644 --- a/09_privilege_level/src/print.rs +++ b/09_privilege_level/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/09_privilege_level/src/synchronization.rs b/09_privilege_level/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/09_privilege_level/src/synchronization.rs +++ b/09_privilege_level/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/09_privilege_level/src/time.rs b/09_privilege_level/src/time.rs index 6d92b196..a9d50120 100644 --- a/09_privilege_level/src/time.rs +++ b/09_privilege_level/src/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Timer primitives. @@ -8,30 +8,50 @@ #[path = "_arch/aarch64/time.rs"] mod arch_time; +use core::time::Duration; + //-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports +// Public Definitions //-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; + +/// Provides time management functions. +pub struct TimeManager; //-------------------------------------------------------------------------------------------------- -// Public Definitions +// Global instances //-------------------------------------------------------------------------------------------------- -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; +static TIME_MANAGER: TimeManager = TimeManager::new(); - /// Time management functions. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; +/// 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. - fn spin_for(&self, duration: Duration); + /// 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/.vscode/settings.json b/10_virtual_mem_part1_identity_mapping/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/10_virtual_mem_part1_identity_mapping/.vscode/settings.json +++ b/10_virtual_mem_part1_identity_mapping/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index 615d5ad8..af2a0a5d 100644 --- a/10_virtual_mem_part1_identity_mapping/Cargo.lock +++ b/10_virtual_mem_part1_identity_mapping/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,12 +15,12 @@ dependencies = [ name = "mingo" version = "0.10.0" dependencies = [ - "cortex-a", + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/10_virtual_mem_part1_identity_mapping/Cargo.toml b/10_virtual_mem_part1_identity_mapping/Cargo.toml index 144767d3..6f12f98e 100644 --- a/10_virtual_mem_part1_identity_mapping/Cargo.toml +++ b/10_virtual_mem_part1_identity_mapping/Cargo.toml @@ -23,8 +23,8 @@ path = "src/main.rs" [dependencies] # Optional dependencies -tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/10_virtual_mem_part1_identity_mapping/Makefile b/10_virtual_mem_part1_identity_mapping/Makefile index e3db66a9..9549f092 100644 --- a/10_virtual_mem_part1_identity_mapping/Makefile +++ b/10_virtual_mem_part1_identity_mapping/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -58,14 +59,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -88,7 +89,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -157,7 +157,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -215,7 +215,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -225,12 +224,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- 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 00000000..2b840e28 --- /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 index 1bf427c0..498ef111 100644 --- a/10_virtual_mem_part1_identity_mapping/README.md +++ b/10_virtual_mem_part1_identity_mapping/README.md @@ -14,7 +14,7 @@ * [Generic Kernel code: `memory/mmu.rs`](#generic-kernel-code-memorymmurs) * [BSP: `bsp/raspberrypi/memory/mmu.rs`](#bsp-bspraspberrypimemorymmurs) * [AArch64: `_arch/aarch64/memory/*`](#aarch64-_archaarch64memory) - * [`link.ld`](#linkld) + * [`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) @@ -218,11 +218,11 @@ 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/crate/cortex-a/5.1.2/source/src/regs/ttbr0_el1.rs -[Translation Control Register - EL1]: https://docs.rs/crate/cortex-a/5.1.2/source/src/regs/tcr_el1.rs -[System Control Register - EL1]: https://docs.rs/crate/cortex-a/5.1.2/source/src/regs/sctlr_el1.rs +[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 -### `link.ld` +### `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: @@ -257,11 +257,11 @@ The MMU init code is again a good example to see the great potential of Rust's z 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: +[aarch64-cpu] 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 +[aarch64-cpu]: https://crates.io/crates/aarch64-cpu ```rust /// Setup function for the MAIR_EL1 register. @@ -296,7 +296,6 @@ Turning on virtual memory is now the first thing we do during kernel init: ```rust unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; use memory::mmu::interface::MMU; if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { @@ -314,6 +313,7 @@ Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now + __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | @@ -325,25 +325,25 @@ Minipush 1.0 [MP] ⏩ Pushing 64 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now -[ 1.034062] mingo version 0.10.0 -[ 1.034270] Booting on: Raspberry Pi 3 -[ 1.034725] MMU online. Special regions: -[ 1.035201] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data -[ 1.036220] 0x1fff0000 - 0x1fffffff | 64 KiB | Dev RW PXN | Remapped Device MMIO -[ 1.037205] 0x3f000000 - 0x4000ffff | 16 MiB | Dev RW PXN | Device MMIO -[ 1.038094] Current privilege level: EL1 -[ 1.038570] Exception handling state: -[ 1.039015] Debug: Masked -[ 1.039405] SError: Masked -[ 1.039794] IRQ: Masked -[ 1.040184] FIQ: Masked -[ 1.040575] Architectural timer resolution: 52 ns -[ 1.041148] Drivers loaded: -[ 1.041484] 1. BCM GPIO -[ 1.041842] 2. BCM PL011 UART -[ 1.042264] Timer test, spinning for 1 second +[ 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 -[ 2.043305] Echoing input now +[ 1.820409] Echoing input now ``` ## Diff to previous @@ -367,7 +367,7 @@ diff -uNr 09_privilege_level/src/_arch/aarch64/memory/mmu/translation_table.rs 1 @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2021-2022 Andre Richter ++// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! @@ -664,7 +664,7 @@ diff -uNr 09_privilege_level/src/_arch/aarch64/memory/mmu.rs 10_virtual_mem_part @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! @@ -681,8 +681,8 @@ diff -uNr 09_privilege_level/src/_arch/aarch64/memory/mmu.rs 10_virtual_mem_part + bsp, memory, + memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, +}; ++use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; -+use cortex_a::{asm::barrier, registers::*}; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- @@ -828,11 +828,11 @@ diff -uNr 09_privilege_level/src/_arch/aarch64/memory/mmu.rs 10_virtual_mem_part + } +} -diff -uNr 09_privilege_level/src/bsp/raspberrypi/link.ld 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld ---- 09_privilege_level/src/bsp/raspberrypi/link.ld -+++ 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld +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-2022 Andre Richter + * Copyright (c) 2018-2023 Andre Richter */ +PAGE_SIZE = 64K; @@ -854,9 +854,9 @@ diff -uNr 09_privilege_level/src/bsp/raspberrypi/link.ld 10_virtual_mem_part1_id .text : { KEEP(*(.text._start)) -@@ -56,6 +62,9 @@ +@@ -55,6 +61,9 @@ + .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; @@ -871,7 +871,7 @@ diff -uNr 09_privilege_level/src/bsp/raspberrypi/memory/mmu.rs 10_virtual_mem_pa @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + @@ -960,7 +960,7 @@ diff -uNr 09_privilege_level/src/bsp/raspberrypi/memory.rs 10_virtual_mem_part1_ --- 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-2022 Andre Richter + // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. +//! @@ -1078,19 +1078,55 @@ diff -uNr 09_privilege_level/src/bsp.rs 10_virtual_mem_part1_identity_mapping/sr #[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 -@@ -105,6 +105,8 @@ +@@ -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)] -@@ -116,6 +118,7 @@ +@@ -118,10 +121,12 @@ + #![no_std] + + mod bsp; ++mod common; + mod console; mod cpu; mod driver; mod exception; @@ -1098,7 +1134,7 @@ diff -uNr 09_privilege_level/src/main.rs 10_virtual_mem_part1_identity_mapping/s mod panic_wait; mod print; mod synchronization; -@@ -126,9 +129,17 @@ +@@ -132,8 +137,17 @@ /// # Safety /// /// - Only a single core must be active and running this function. @@ -1108,16 +1144,25 @@ diff -uNr 09_privilege_level/src/main.rs 10_virtual_mem_part1_identity_mapping/s +/// 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 driver::interface::DriverManager; + 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 @@ - for i in bsp::driver::driver_manager().all_device_drivers().iter() { - if let Err(x) = i.init() { -@@ -157,6 +168,9 @@ + /// 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()); @@ -1127,7 +1172,7 @@ diff -uNr 09_privilege_level/src/main.rs 10_virtual_mem_part1_identity_mapping/s let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); -@@ -180,6 +194,13 @@ +@@ -176,6 +193,13 @@ info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); @@ -1148,7 +1193,7 @@ diff -uNr 09_privilege_level/src/memory/mmu/translation_table.rs 10_virtual_mem_ @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2021-2022 Andre Richter ++// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + @@ -1164,10 +1209,10 @@ diff -uNr 09_privilege_level/src/memory/mmu/translation_table.rs 10_virtual_mem_ 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,264 @@ +@@ -0,0 +1,253 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2020-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. +//! @@ -1187,6 +1232,7 @@ diff -uNr 09_privilege_level/src/memory/mmu.rs 10_virtual_mem_part1_identity_map + +mod translation_table; + ++use crate::common; +use core::{fmt, ops::RangeInclusive}; + +//-------------------------------------------------------------------------------------------------- @@ -1346,19 +1392,7 @@ diff -uNr 09_privilege_level/src/memory/mmu.rs 10_virtual_mem_part1_identity_map + 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 (size, unit) = common::size_human_readable_ceil(size); + + let attr = match self.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", @@ -1436,7 +1470,7 @@ diff -uNr 09_privilege_level/src/memory.rs 10_virtual_mem_part1_identity_mapping @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + 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 index 4414ac6a..602c9789 100644 --- a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code 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 index f677c9c4..c80f3ebb 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,12 +11,16 @@ //! //! crate::cpu::boot::arch_boot +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; -use cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Private Code 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 index 28b35087..f6df2123 100644 --- 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 @@ -18,9 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _EL2, 0x8 -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -32,12 +29,12 @@ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL - cmp x0, _EL2 + 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, _core_id_mask + 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 @@ -60,6 +57,14 @@ _start: 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 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 index c8eac4f0..1051af6a 100644 --- a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! @@ -11,7 +11,7 @@ //! //! crate::exception::arch_exception -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- 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 index e3e3672e..65fcad25 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! @@ -11,7 +11,7 @@ //! //! crate::exception::asynchronous::arch_asynchronous -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- 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 index 3a965f71..eea4465c 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! @@ -17,8 +17,8 @@ use crate::{ bsp, memory, memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, }; +use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- 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 index 057335c4..f3d8f619 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! 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 index c814219c..ee1c3ef7 100644 --- a/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs +++ b/10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural timer primitives. //! @@ -11,111 +11,152 @@ //! //! crate::time::arch_time -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; +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; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } +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) } } -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER +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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; + // 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(); - let x = match frq.checked_mul(duration.as_nanos() as u64) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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. +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 index 2e860ecb..7a3c804b 100644 --- a/10_virtual_mem_part1_identity_mapping/src/bsp.rs +++ b/10_virtual_mem_part1_identity_mapping/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. 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 index 6e9bf8f3..64049a4c 100644 --- a/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. 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 index b4b7906e..1c343d1d 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. 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 index dbb4beaa..8e57dfed 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -143,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. @@ -189,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -214,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/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 index 878ea567..d92612ea 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -326,7 +323,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -346,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> { @@ -364,7 +367,7 @@ 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)) } @@ -400,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/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 index fd9e988e..dfe7d8ef 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs index 22edb4fa..3ea864dc 100644 --- a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs @@ -1,25 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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) }; - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- diff --git a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/console.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/console.rs deleted file mode 100644 index a247032f..00000000 --- a/10_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-2022 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_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. 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 index b5538baa..2a80ee2c 100644 --- a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs @@ -1,49 +1,71 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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/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 00000000..3ce16cce --- /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 index 7a57b618..661476f4 100644 --- a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs +++ b/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! 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 index ea43f899..6c2414f7 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. 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 00000000..782a5da1 --- /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 index e49e241f..a83f86fe 100644 --- a/10_virtual_mem_part1_identity_mapping/src/console.rs +++ b/10_virtual_mem_part1_identity_mapping/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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/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 00000000..e92a022b --- /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 index 62503fb4..67ab79c0 100644 --- a/10_virtual_mem_part1_identity_mapping/src/cpu.rs +++ b/10_virtual_mem_part1_identity_mapping/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/10_virtual_mem_part1_identity_mapping/src/cpu/boot.rs b/10_virtual_mem_part1_identity_mapping/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/10_virtual_mem_part1_identity_mapping/src/cpu/boot.rs +++ b/10_virtual_mem_part1_identity_mapping/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/10_virtual_mem_part1_identity_mapping/src/driver.rs b/10_virtual_mem_part1_identity_mapping/src/driver.rs index 2fcc7562..050e7022 100644 --- a/10_virtual_mem_part1_identity_mapping/src/driver.rs +++ b/10_virtual_mem_part1_identity_mapping/src/driver.rs @@ -1,9 +1,25 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// 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 //-------------------------------------------------------------------------------------------------- @@ -24,21 +40,128 @@ 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>; + +/// 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()), + } + } - /// Device driver management functions. + /// 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 + ); + } + } + }); + } + + /// 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 index b80248f7..45760391 100644 --- a/10_virtual_mem_part1_identity_mapping/src/exception.rs +++ b/10_virtual_mem_part1_identity_mapping/src/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. @@ -21,7 +21,7 @@ pub use arch_exception::current_privilege_level; /// Kernel privilege levels. #[allow(missing_docs)] -#[derive(PartialEq)] +#[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, diff --git a/10_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs b/10_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs index bad85779..fd059326 100644 --- a/10_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs +++ b/10_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Asynchronous exception handling. diff --git a/10_virtual_mem_part1_identity_mapping/src/main.rs b/10_virtual_mem_part1_identity_mapping/src/main.rs index faa81ee8..52ce7d98 100644 --- a/10_virtual_mem_part1_identity_mapping/src/main.rs +++ b/10_virtual_mem_part1_identity_mapping/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -106,14 +108,20 @@ #![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; @@ -134,19 +142,19 @@ mod time; /// 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 driver::interface::DriverManager; use memory::mmu::interface::MMU; if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { 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); - } + // 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. @@ -155,11 +163,8 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; + use console::{console, interface::Write}; use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; info!( "{} version {}", @@ -183,13 +188,7 @@ fn kernel_main() -> ! { ); info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); @@ -206,7 +205,7 @@ fn kernel_main() -> ! { // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); + 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 index ac6663b3..6dd8f186 100644 --- a/10_virtual_mem_part1_identity_mapping/src/memory.rs +++ b/10_virtual_mem_part1_identity_mapping/src/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management. diff --git a/10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs b/10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs index 17a98274..87ed1efb 100644 --- a/10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs +++ b/10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. //! @@ -20,6 +20,7 @@ mod arch_mmu; mod translation_table; +use crate::common; use core::{fmt, ops::RangeInclusive}; //-------------------------------------------------------------------------------------------------- @@ -179,19 +180,7 @@ impl fmt::Display for TranslationDescriptor { 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 (size, unit) = common::size_human_readable_ceil(size); let attr = match self.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", 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 index 88e3fe48..1a2581aa 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Translation table. diff --git a/10_virtual_mem_part1_identity_mapping/src/panic_wait.rs b/10_virtual_mem_part1_identity_mapping/src/panic_wait.rs index f851e0d8..5776aca8 100644 --- a/10_virtual_mem_part1_identity_mapping/src/panic_wait.rs +++ b/10_virtual_mem_part1_identity_mapping/src/panic_wait.rs @@ -1,32 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -58,8 +42,6 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -69,7 +51,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/10_virtual_mem_part1_identity_mapping/src/print.rs b/10_virtual_mem_part1_identity_mapping/src/print.rs index 9ec13a28..8e303046 100644 --- a/10_virtual_mem_part1_identity_mapping/src/print.rs +++ b/10_virtual_mem_part1_identity_mapping/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/10_virtual_mem_part1_identity_mapping/src/synchronization.rs b/10_virtual_mem_part1_identity_mapping/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/10_virtual_mem_part1_identity_mapping/src/synchronization.rs +++ b/10_virtual_mem_part1_identity_mapping/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/10_virtual_mem_part1_identity_mapping/src/time.rs b/10_virtual_mem_part1_identity_mapping/src/time.rs index 6d92b196..a9d50120 100644 --- a/10_virtual_mem_part1_identity_mapping/src/time.rs +++ b/10_virtual_mem_part1_identity_mapping/src/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Timer primitives. @@ -8,30 +8,50 @@ #[path = "_arch/aarch64/time.rs"] mod arch_time; +use core::time::Duration; + //-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports +// Public Definitions //-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; + +/// Provides time management functions. +pub struct TimeManager; //-------------------------------------------------------------------------------------------------- -// Public Definitions +// Global instances //-------------------------------------------------------------------------------------------------- -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; +static TIME_MANAGER: TimeManager = TimeManager::new(); - /// Time management functions. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; +/// 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. - fn spin_for(&self, duration: Duration); + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) } } diff --git a/11_exceptions_part1_groundwork/.vscode/settings.json b/11_exceptions_part1_groundwork/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/11_exceptions_part1_groundwork/.vscode/settings.json +++ b/11_exceptions_part1_groundwork/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index 9eae6c69..dd741b8d 100644 --- a/11_exceptions_part1_groundwork/Cargo.lock +++ b/11_exceptions_part1_groundwork/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,12 +15,12 @@ dependencies = [ name = "mingo" version = "0.11.0" dependencies = [ - "cortex-a", + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/11_exceptions_part1_groundwork/Cargo.toml b/11_exceptions_part1_groundwork/Cargo.toml index aa8a870c..22343d4c 100644 --- a/11_exceptions_part1_groundwork/Cargo.toml +++ b/11_exceptions_part1_groundwork/Cargo.toml @@ -23,8 +23,8 @@ path = "src/main.rs" [dependencies] # Optional dependencies -tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/11_exceptions_part1_groundwork/Makefile b/11_exceptions_part1_groundwork/Makefile index e3db66a9..9549f092 100644 --- a/11_exceptions_part1_groundwork/Makefile +++ b/11_exceptions_part1_groundwork/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -58,14 +59,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -88,7 +89,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -157,7 +157,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -215,7 +215,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -225,12 +224,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/11_exceptions_part1_groundwork/README.md b/11_exceptions_part1_groundwork/README.md index 2f90b7ff..7de4e306 100644 --- a/11_exceptions_part1_groundwork/README.md +++ b/11_exceptions_part1_groundwork/README.md @@ -183,6 +183,7 @@ some hand-crafted assembly. Introducing `exception.s`: /// 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 @@ -221,6 +222,9 @@ some hand-crafted assembly. Introducing `exception.s`: // 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 ``` @@ -324,7 +328,7 @@ The actual handlers referenced from the assembly can now branch to it for the ti ```rust #[no_mangle] -unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { +extern "C" fn current_elx_irq(e: &mut ExceptionContext) { default_exception_handler(e); } ``` @@ -363,7 +367,7 @@ 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) { +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { if e.fault_address_valid() { let far_el1 = FAR_EL1.get(); @@ -413,31 +417,31 @@ Minipush 1.0 [MP] ⏩ Pushing 64 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now -[ 0.787414] mingo version 0.11.0 -[ 0.787621] Booting on: Raspberry Pi 3 -[ 0.788076] MMU online. Special regions: -[ 0.788553] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data -[ 0.789571] 0x3f000000 - 0x4000ffff | 16 MiB | Dev RW PXN | Device MMIO -[ 0.790460] Current privilege level: EL1 -[ 0.790936] Exception handling state: -[ 0.791380] Debug: Masked -[ 0.791770] SError: Masked -[ 0.792160] IRQ: Masked -[ 0.792550] FIQ: Masked -[ 0.792940] Architectural timer resolution: 52 ns -[ 0.793514] Drivers loaded: -[ 0.793850] 1. BCM GPIO -[ 0.794208] 2. BCM PL011 UART -[ 0.794630] Timer test, spinning for 1 second -[ 1.795161] -[ 1.795165] Trying to read from address 8 GiB... -[ 1.795715] ************************************************ -[ 1.796407] Whoa! We recovered from a synchronous exception! -[ 1.797100] ************************************************ -[ 1.797794] -[ 1.797967] Let's try again -[ 1.798303] Trying to read from address 9 GiB... -[ 1.798867] Kernel panic! +[ 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 @@ -460,25 +464,25 @@ SPSR_EL1: 0x600003c5 IRQ (I): Masked FIQ (F): Masked Illegal Execution State (IL): Not set -ELR_EL1: 0x0000000000082194 +ELR_EL1: 0x00000000000845f8 General purpose register: - x0 : 0x0000000000000000 x1 : 0x0000000000085517 - x2 : 0x0000000000000027 x3 : 0x0000000000084380 - x4 : 0x0000000000000006 x5 : 0xfb5f341800000000 - x6 : 0x0000000000000000 x7 : 0x7f91bc012b2b0209 - x8 : 0x0000000240000000 x9 : 0x0000000000085517 + 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: 0x0000000000000030 x19: 0x0000000000090008 - x20: 0x0000000000085350 x21: 0x000000003b9aca00 - x22: 0x0000000000082e4c x23: 0x0000000000082308 + x18: 0x00000000000c58fc x19: 0x0000000000090008 + x20: 0x0000000000085fc0 x21: 0x000000003b9aca00 + x22: 0x0000000000082238 x23: 0x00000000000813d4 x24: 0x0000000010624dd3 x25: 0xffffffffc4653600 - x26: 0x0000000000086638 x27: 0x0000000000085410 - x28: 0x0000000000084f90 x29: 0x0000000000086538 - lr : 0x0000000000082188 + x26: 0x0000000000086988 x27: 0x0000000000086080 + x28: 0x0000000000085f10 x29: 0x0000000000085c00 + lr : 0x00000000000845ec ``` ## Diff to previous @@ -503,10 +507,10 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 1 //! //! crate::exception::arch_exception --use cortex_a::registers::*; +-use aarch64_cpu::registers::*; -use tock_registers::interfaces::Readable; ++use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; -+use cortex_a::{asm::barrier, registers::*}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, @@ -539,7 +543,7 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 1 + /// Saved program status. + spsr_el1: SpsrEL1, + -+ // Exception syndrome register. ++ /// Exception syndrome register. + esr_el1: EsrEL1, +} + @@ -561,17 +565,17 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 1 +//------------------------------------------------------------------------------ + +#[no_mangle] -+unsafe extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { ++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] -+unsafe extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { ++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] -+unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { ++extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + @@ -580,7 +584,7 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 1 +//------------------------------------------------------------------------------ + +#[no_mangle] -+unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { ++extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + if e.fault_address_valid() { + let far_el1 = FAR_EL1.get(); + @@ -597,12 +601,12 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 1 +} + +#[no_mangle] -+unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { ++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) { ++extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + @@ -611,17 +615,17 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 1 +//------------------------------------------------------------------------------ + +#[no_mangle] -+unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { ++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) { ++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) { ++extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + @@ -630,17 +634,17 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 1 +//------------------------------------------------------------------------------ + +#[no_mangle] -+unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { ++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) { ++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) { ++extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + @@ -793,10 +797,10 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 1 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,150 @@ +@@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// -+// Copyright (c) 2018-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions @@ -805,6 +809,7 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.s 11 +/// 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 + @@ -843,6 +848,9 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.s 11 + // 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 @@ -1016,8 +1024,8 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/exception.rs 11_exceptions_p 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 -@@ -137,6 +137,8 @@ - use driver::interface::DriverManager; +@@ -144,6 +144,8 @@ + unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; + exception::handling_init(); @@ -1025,7 +1033,16 @@ diff -uNr 10_virtual_mem_part1_identity_mapping/src/main.rs 11_exceptions_part1_ if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { panic!("MMU: {}", string); } -@@ -194,13 +196,28 @@ +@@ -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)); diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs index 4414ac6a..602c9789 100644 --- a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.rs index f677c9c4..c80f3ebb 100644 --- a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.rs +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,12 +11,16 @@ //! //! crate::cpu::boot::arch_boot +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; -use cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Private Code diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.s b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.s index 28b35087..f6df2123 100644 --- a/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.s +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.s @@ -18,9 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _EL2, 0x8 -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -32,12 +29,12 @@ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL - cmp x0, _EL2 + 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, _core_id_mask + 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 @@ -60,6 +57,14 @@ _start: 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 diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs index e8484938..9d2ed5b7 100644 --- a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! @@ -11,8 +11,8 @@ //! //! crate::exception::arch_exception +use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::InMemoryRegister, @@ -45,7 +45,7 @@ struct ExceptionContext { /// Saved program status. spsr_el1: SpsrEL1, - // Exception syndrome register. + /// Exception syndrome register. esr_el1: EsrEL1, } @@ -67,17 +67,17 @@ fn default_exception_handler(exc: &ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } @@ -86,7 +86,7 @@ unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { if e.fault_address_valid() { let far_el1 = FAR_EL1.get(); @@ -103,12 +103,12 @@ unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { } #[no_mangle] -unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { +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) { +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -117,17 +117,17 @@ unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -136,17 +136,17 @@ unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s index 5aae30b9..91805ee7 100644 --- a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s @@ -9,6 +9,7 @@ /// 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 @@ -47,6 +48,9 @@ // 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 diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs index e3e3672e..65fcad25 100644 --- a/11_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! @@ -11,7 +11,7 @@ //! //! crate::exception::asynchronous::arch_asynchronous -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs index 3a965f71..eea4465c 100644 --- a/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! @@ -17,8 +17,8 @@ use crate::{ bsp, memory, memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, }; +use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- 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 index 057335c4..f3d8f619 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! diff --git a/11_exceptions_part1_groundwork/src/_arch/aarch64/time.rs b/11_exceptions_part1_groundwork/src/_arch/aarch64/time.rs index c814219c..ee1c3ef7 100644 --- a/11_exceptions_part1_groundwork/src/_arch/aarch64/time.rs +++ b/11_exceptions_part1_groundwork/src/_arch/aarch64/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural timer primitives. //! @@ -11,111 +11,152 @@ //! //! crate::time::arch_time -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; +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; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } +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) } } -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER +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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; + // 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(); - let x = match frq.checked_mul(duration.as_nanos() as u64) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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. +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 index 824787f6..246973bc 100644 --- a/11_exceptions_part1_groundwork/src/bsp.rs +++ b/11_exceptions_part1_groundwork/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/11_exceptions_part1_groundwork/src/bsp/device_driver.rs b/11_exceptions_part1_groundwork/src/bsp/device_driver.rs index 6e9bf8f3..64049a4c 100644 --- a/11_exceptions_part1_groundwork/src/bsp/device_driver.rs +++ b/11_exceptions_part1_groundwork/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs b/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs index b4b7906e..1c343d1d 100644 --- a/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs +++ b/11_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. 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 index dbb4beaa..8e57dfed 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -143,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. @@ -189,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -214,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/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 index 878ea567..d92612ea 100644 --- 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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -326,7 +323,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -346,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> { @@ -364,7 +367,7 @@ 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)) } @@ -400,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/11_exceptions_part1_groundwork/src/bsp/device_driver/common.rs b/11_exceptions_part1_groundwork/src/bsp/device_driver/common.rs index fd9e988e..dfe7d8ef 100644 --- a/11_exceptions_part1_groundwork/src/bsp/device_driver/common.rs +++ b/11_exceptions_part1_groundwork/src/bsp/device_driver/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi.rs index 22edb4fa..3ea864dc 100644 --- a/11_exceptions_part1_groundwork/src/bsp/raspberrypi.rs +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi.rs @@ -1,25 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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) }; - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs deleted file mode 100644 index a247032f..00000000 --- a/11_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-2022 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_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs index b5538baa..2a80ee2c 100644 --- a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs @@ -1,49 +1,71 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/kernel.ld similarity index 88% rename from 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld rename to 11_exceptions_part1_groundwork/src/bsp/raspberrypi/kernel.ld index 2ce4b44b..6d939889 100644 --- a/10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/link.ld +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/kernel.ld @@ -60,7 +60,6 @@ SECTIONS } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; @@ -78,4 +77,12 @@ SECTIONS . = 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 index 7a57b618..661476f4 100644 --- a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! diff --git a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs index 2b3a609b..6009ace4 100644 --- a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs +++ b/11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. diff --git a/11_exceptions_part1_groundwork/src/common.rs b/11_exceptions_part1_groundwork/src/common.rs new file mode 100644 index 00000000..782a5da1 --- /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 index e49e241f..a83f86fe 100644 --- a/11_exceptions_part1_groundwork/src/console.rs +++ b/11_exceptions_part1_groundwork/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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/11_exceptions_part1_groundwork/src/console/null_console.rs b/11_exceptions_part1_groundwork/src/console/null_console.rs new file mode 100644 index 00000000..e92a022b --- /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 index 62503fb4..67ab79c0 100644 --- a/11_exceptions_part1_groundwork/src/cpu.rs +++ b/11_exceptions_part1_groundwork/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/11_exceptions_part1_groundwork/src/cpu/boot.rs b/11_exceptions_part1_groundwork/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/11_exceptions_part1_groundwork/src/cpu/boot.rs +++ b/11_exceptions_part1_groundwork/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/11_exceptions_part1_groundwork/src/driver.rs b/11_exceptions_part1_groundwork/src/driver.rs index 2fcc7562..050e7022 100644 --- a/11_exceptions_part1_groundwork/src/driver.rs +++ b/11_exceptions_part1_groundwork/src/driver.rs @@ -1,9 +1,25 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// 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 //-------------------------------------------------------------------------------------------------- @@ -24,21 +40,128 @@ 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>; + +/// 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()), + } + } - /// Device driver management functions. + /// 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 + ); + } + } + }); + } + + /// 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 index 696787c1..77b58248 100644 --- a/11_exceptions_part1_groundwork/src/exception.rs +++ b/11_exceptions_part1_groundwork/src/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. @@ -21,7 +21,7 @@ pub use arch_exception::{current_privilege_level, handling_init}; /// Kernel privilege levels. #[allow(missing_docs)] -#[derive(PartialEq)] +#[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, diff --git a/11_exceptions_part1_groundwork/src/exception/asynchronous.rs b/11_exceptions_part1_groundwork/src/exception/asynchronous.rs index bad85779..fd059326 100644 --- a/11_exceptions_part1_groundwork/src/exception/asynchronous.rs +++ b/11_exceptions_part1_groundwork/src/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Asynchronous exception handling. diff --git a/11_exceptions_part1_groundwork/src/main.rs b/11_exceptions_part1_groundwork/src/main.rs index 77ffd9cd..fc01bb3b 100644 --- a/11_exceptions_part1_groundwork/src/main.rs +++ b/11_exceptions_part1_groundwork/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -106,14 +108,20 @@ #![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; @@ -134,7 +142,6 @@ mod time; /// 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 driver::interface::DriverManager; use memory::mmu::interface::MMU; exception::handling_init(); @@ -143,12 +150,13 @@ unsafe fn kernel_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); - } + // 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. @@ -157,11 +165,8 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; + use console::console; use core::time::Duration; - use driver::interface::DriverManager; - use time::interface::TimeManager; info!( "{} version {}", @@ -185,13 +190,7 @@ fn kernel_main() -> ! { ); info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); @@ -223,7 +222,7 @@ fn kernel_main() -> ! { // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); + 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 index ac6663b3..6dd8f186 100644 --- a/11_exceptions_part1_groundwork/src/memory.rs +++ b/11_exceptions_part1_groundwork/src/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management. diff --git a/11_exceptions_part1_groundwork/src/memory/mmu.rs b/11_exceptions_part1_groundwork/src/memory/mmu.rs index 17a98274..87ed1efb 100644 --- a/11_exceptions_part1_groundwork/src/memory/mmu.rs +++ b/11_exceptions_part1_groundwork/src/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. //! @@ -20,6 +20,7 @@ mod arch_mmu; mod translation_table; +use crate::common; use core::{fmt, ops::RangeInclusive}; //-------------------------------------------------------------------------------------------------- @@ -179,19 +180,7 @@ impl fmt::Display for TranslationDescriptor { 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 (size, unit) = common::size_human_readable_ceil(size); let attr = match self.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", diff --git a/11_exceptions_part1_groundwork/src/memory/mmu/translation_table.rs b/11_exceptions_part1_groundwork/src/memory/mmu/translation_table.rs index 88e3fe48..1a2581aa 100644 --- a/11_exceptions_part1_groundwork/src/memory/mmu/translation_table.rs +++ b/11_exceptions_part1_groundwork/src/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Translation table. diff --git a/11_exceptions_part1_groundwork/src/panic_wait.rs b/11_exceptions_part1_groundwork/src/panic_wait.rs index f851e0d8..5776aca8 100644 --- a/11_exceptions_part1_groundwork/src/panic_wait.rs +++ b/11_exceptions_part1_groundwork/src/panic_wait.rs @@ -1,32 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -58,8 +42,6 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -69,7 +51,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/11_exceptions_part1_groundwork/src/print.rs b/11_exceptions_part1_groundwork/src/print.rs index 9ec13a28..8e303046 100644 --- a/11_exceptions_part1_groundwork/src/print.rs +++ b/11_exceptions_part1_groundwork/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/11_exceptions_part1_groundwork/src/synchronization.rs b/11_exceptions_part1_groundwork/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/11_exceptions_part1_groundwork/src/synchronization.rs +++ b/11_exceptions_part1_groundwork/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/11_exceptions_part1_groundwork/src/time.rs b/11_exceptions_part1_groundwork/src/time.rs index 6d92b196..a9d50120 100644 --- a/11_exceptions_part1_groundwork/src/time.rs +++ b/11_exceptions_part1_groundwork/src/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Timer primitives. @@ -8,30 +8,50 @@ #[path = "_arch/aarch64/time.rs"] mod arch_time; +use core::time::Duration; + //-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports +// Public Definitions //-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; + +/// Provides time management functions. +pub struct TimeManager; //-------------------------------------------------------------------------------------------------- -// Public Definitions +// Global instances //-------------------------------------------------------------------------------------------------- -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; +static TIME_MANAGER: TimeManager = TimeManager::new(); - /// Time management functions. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; +/// 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. - fn spin_for(&self, duration: Duration); + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) } } diff --git a/12_integrated_testing/.vscode/settings.json b/12_integrated_testing/.vscode/settings.json index 0a8d7c09..9ef30cd0 100644 --- a/12_integrated_testing/.vscode/settings.json +++ b/12_integrated_testing/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index d34ce134..8db3db87 100644 --- a/12_integrated_testing/Cargo.lock +++ b/12_integrated_testing/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,8 +15,7 @@ dependencies = [ name = "mingo" version = "0.12.0" dependencies = [ - "cortex-a", - "mingo", + "aarch64-cpu", "qemu-exit", "test-macros", "test-types", @@ -25,11 +24,11 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.37" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" dependencies = [ - "unicode-xid", + "unicode-ident", ] [[package]] @@ -40,22 +39,22 @@ checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" [[package]] name = "quote" -version = "1.0.17" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "syn" -version = "1.0.91" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" dependencies = [ "proc-macro2", "quote", - "unicode-xid", + "unicode-ident", ] [[package]] @@ -74,12 +73,12 @@ version = "0.1.0" [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" [[package]] -name = "unicode-xid" -version = "0.2.2" +name = "unicode-ident" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/12_integrated_testing/Cargo.toml b/12_integrated_testing/Cargo.toml index 3e4b2a8a..6480a727 100644 --- a/12_integrated_testing/Cargo.toml +++ b/12_integrated_testing/Cargo.toml @@ -1,67 +1,9 @@ -[package] -name = "mingo" -version = "0.12.0" -authors = ["Andre Richter "] -edition = "2021" +[workspace] + +members = [ + "libraries/*", + "kernel" +] [profile.release] lto = true - -[features] -default = [] -bsp_rpi3 = ["tock-registers"] -bsp_rpi4 = ["tock-registers"] -test_build = ["qemu-exit"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] -test-types = { path = "test-types" } - -# Optional dependencies -tock-registers = { version = "0.7.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] -cortex-a = { version = "7.x.x" } - -##-------------------------------------------------------------------------------------------------- -## Testing -##-------------------------------------------------------------------------------------------------- - -[dev-dependencies] -test-macros = { path = "test-macros" } - -# The following line is a workaround, as suggested in [1], to enable a feature in test-builds only. -# This allows building the library part of the kernel with specialized code for testing. -# -# -# [1] https://github.com/rust-lang/cargo/issues/2911#issuecomment-749580481 -mingo = { path = ".", features = ["test_build"] } - -# 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/Makefile b/12_integrated_testing/Makefile index afa22480..4e2efeff 100644 --- a/12_integrated_testing/Makefile +++ b/12_integrated_testing/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -41,7 +42,7 @@ ifeq ($(BSP),rpi3) 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 + 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 @@ -55,7 +56,7 @@ else ifeq ($(BSP),rpi4) 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 + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif @@ -67,14 +68,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -94,11 +95,10 @@ COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -TEST_CMD = cargo test $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary @@ -167,7 +167,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -203,6 +203,8 @@ chainboot: $(KERNEL_BIN) ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean @@ -225,7 +227,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -235,12 +236,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- @@ -277,6 +272,8 @@ gdb gdb-opt0: $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- .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: @@ -295,7 +292,11 @@ test_boot: $(KERNEL_BIN) ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER - #!/usr/bin/env bash +#!/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') diff --git a/12_integrated_testing/README.md b/12_integrated_testing/README.md index 05029ca1..ae68d269 100644 --- a/12_integrated_testing/README.md +++ b/12_integrated_testing/README.md @@ -16,6 +16,7 @@ - [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) @@ -82,6 +83,24 @@ 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: @@ -104,8 +123,8 @@ test: test_boot test_unit test_integration ### 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: +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 @@ -126,10 +145,10 @@ of the kernel code. The `main.rs` file is stripped down to the minimum. It only `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: +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] @@ -193,10 +212,10 @@ pub fn test_runner(tests: &[&test_types::UnitTest]) { 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: +`$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 @@ -248,7 +267,7 @@ implementation in `lib.rs`: #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); test_main(); @@ -256,7 +275,7 @@ unsafe fn kernel_init() -> ! { } ``` -Note the call to `bsp::console::qemu_bring_up_console()`. Since we are running all our tests inside +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 @@ -324,7 +343,7 @@ pub fn qemu_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 `Cargo.toml`, we ensure that +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. @@ -396,6 +415,10 @@ The file `kernel_test_runner.sh` does not exist by default. We generate it on de 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') @@ -426,7 +449,7 @@ provided to it by `cargo`, and finally compiles a `docker` command to execute th reference, here it is fully resolved for an `RPi3 BSP`: ```bash -docker run --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 ruby ../common/tests/dispatch.rb qemu-system-aarch64 -M raspi3 -serial stdio -display none -semihosting -kernel $TEST_BINARY +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 @@ -441,17 +464,16 @@ executed successfully, which can be checked by inspecting `QEMU`'s exit code. So the provided qemu command it got from `ARGV`, and creates and runs an instance of `ExitCodeTest`: ```ruby -require_relative 'boot_test' -require_relative 'console_io_test' -require_relative '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 'tests/boot_test_string.rb' # provides 'EXPECTED_PRINT' + load "#{path_prefix}tests/boot_test_string.rb" # provides 'EXPECTED_PRINT' BootTest.new(qemu_cmd, EXPECTED_PRINT).run # Doesn't return when 'libkernel' @@ -566,7 +588,7 @@ mod tests { ``` 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. +`$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:. @@ -598,13 +620,13 @@ your test code into individual chunks. For example, take a look at `tests/01_tim #![test_runner(libkernel::test_runner)] use core::time::Duration; -use libkernel::{bsp, cpu, exception, time, time::interface::TimeManager}; +use libkernel::{bsp, cpu, exception, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. @@ -622,6 +644,7 @@ fn timer_is_counting() { /// 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) } ``` @@ -633,9 +656,9 @@ Note how the `test_runner` from `libkernel` is pulled in through 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: +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. @@ -692,14 +715,14 @@ so the wanted outcome is a `panic!`. Here is the whole test (minus some inline c mod panic_exit_success; -use libkernel::{bsp, cpu, exception, memory, println}; +use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + 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"); @@ -740,7 +763,7 @@ Here is an excerpt from `00_console_sanity.rb` showing a subtest that does a han kernel over the console: ```ruby -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify sending and receiving works as expected. class TxRxHandshakeTest < SubtestBase @@ -770,11 +793,10 @@ use libkernel::{bsp, console, cpu, exception, print}; #[no_mangle] unsafe fn kernel_init() -> ! { - use bsp::console::console; - use console::interface::*; + use console::console; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); @@ -890,1289 +912,12 @@ Compiling integration test(s) - rpi3 ``` ## Diff to previous -```diff - -diff -uNr 11_exceptions_part1_groundwork/.cargo/config.toml 12_integrated_testing/.cargo/config.toml ---- 11_exceptions_part1_groundwork/.cargo/config.toml -+++ 12_integrated_testing/.cargo/config.toml -@@ -0,0 +1,2 @@ -+[target.'cfg(target_os = "none")'] -+runner = "target/kernel_test_runner.sh" - -diff -uNr 11_exceptions_part1_groundwork/Cargo.toml 12_integrated_testing/Cargo.toml ---- 11_exceptions_part1_groundwork/Cargo.toml -+++ 12_integrated_testing/Cargo.toml -@@ -1,6 +1,6 @@ - [package] - name = "mingo" --version = "0.11.0" -+version = "0.12.0" - authors = ["Andre Richter "] - edition = "2021" - -@@ -11,20 +11,57 @@ - default = [] - bsp_rpi3 = ["tock-registers"] - bsp_rpi4 = ["tock-registers"] -- --[[bin]] --name = "kernel" --path = "src/main.rs" -+test_build = ["qemu-exit"] - - ##-------------------------------------------------------------------------------------------------- - ## Dependencies - ##-------------------------------------------------------------------------------------------------- - - [dependencies] -+test-types = { path = "test-types" } - - # Optional dependencies - tock-registers = { version = "0.7.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] - cortex-a = { version = "7.x.x" } -+ -+##-------------------------------------------------------------------------------------------------- -+## Testing -+##-------------------------------------------------------------------------------------------------- -+ -+[dev-dependencies] -+test-macros = { path = "test-macros" } -+ -+# The following line is a workaround, as suggested in [1], to enable a feature in test-builds only. -+# This allows building the library part of the kernel with specialized code for testing. -+# -+# -+# [1] https://github.com/rust-lang/cargo/issues/2911#issuecomment-749580481 -+mingo = { path = ".", features = ["test_build"] } -+ -+# 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 -uNr 11_exceptions_part1_groundwork/Makefile 12_integrated_testing/Makefile ---- 11_exceptions_part1_groundwork/Makefile -+++ 12_integrated_testing/Makefile -@@ -15,6 +15,13 @@ - # 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 -+ - - - ##-------------------------------------------------------------------------------------------------- -@@ -28,6 +35,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 - READELF_BINARY = aarch64-none-elf-readelf -@@ -41,6 +49,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 - READELF_BINARY = aarch64-none-elf-readelf -@@ -89,6 +98,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 -@@ -265,11 +275,11 @@ - ##-------------------------------------------------------------------------------------------------- - ## Testing targets - ##-------------------------------------------------------------------------------------------------- --.PHONY: test test_boot -+.PHONY: test test_boot test_unit test_integration - - ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. - --test_boot test: -+test_boot test_unit test_integration test: - $(call color_header, "$(QEMU_MISSING_STRING)") - - else # QEMU is supported. -@@ -281,6 +291,43 @@ - $(call color_header, "Boot test - $(BSP)") - @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) - --test: test_boot -+##------------------------------------------------------------------------------ -+## Helpers for unit and integration test targets -+##------------------------------------------------------------------------------ -+define KERNEL_TEST_RUNNER -+ #!/usr/bin/env bash -+ -+ 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 -uNr 11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs 12_integrated_testing/src/_arch/aarch64/cpu.rs ---- 11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs -+++ 12_integrated_testing/src/_arch/aarch64/cpu.rs -@@ -26,3 +26,24 @@ - 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 -uNr 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs 12_integrated_testing/src/_arch/aarch64/exception.rs ---- 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs -+++ 12_integrated_testing/src/_arch/aarch64/exception.rs -@@ -87,15 +87,14 @@ - - #[no_mangle] - unsafe 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; -+ #[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; -+ } - } - } - -@@ -192,6 +191,12 @@ - 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. - -diff -uNr 11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu/translation_table.rs 12_integrated_testing/src/_arch/aarch64/memory/mmu/translation_table.rs ---- 11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu/translation_table.rs -+++ 12_integrated_testing/src/_arch/aarch64/memory/mmu/translation_table.rs -@@ -290,3 +290,31 @@ - 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 -uNr 11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs 12_integrated_testing/src/_arch/aarch64/memory/mmu.rs ---- 11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs -+++ 12_integrated_testing/src/_arch/aarch64/memory/mmu.rs -@@ -163,3 +163,33 @@ - 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 11_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs 12_integrated_testing/src/bsp/raspberrypi/console.rs ---- 11_exceptions_part1_groundwork/src/bsp/raspberrypi/console.rs -+++ 12_integrated_testing/src/bsp/raspberrypi/console.rs -@@ -35,3 +35,14 @@ - 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. -+#[cfg(feature = "test_build")] -+pub fn qemu_bring_up_console() {} - -diff -uNr 11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs 12_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs ---- 11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs -+++ 12_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs -@@ -69,3 +69,46 @@ - 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 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 11_exceptions_part1_groundwork/src/cpu.rs 12_integrated_testing/src/cpu.rs ---- 11_exceptions_part1_groundwork/src/cpu.rs -+++ 12_integrated_testing/src/cpu.rs -@@ -14,3 +14,6 @@ - // 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 -uNr 11_exceptions_part1_groundwork/src/exception.rs 12_integrated_testing/src/exception.rs ---- 11_exceptions_part1_groundwork/src/exception.rs -+++ 12_integrated_testing/src/exception.rs -@@ -28,3 +28,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 11_exceptions_part1_groundwork/src/lib.rs 12_integrated_testing/src/lib.rs ---- 11_exceptions_part1_groundwork/src/lib.rs -+++ 12_integrated_testing/src/lib.rs -@@ -0,0 +1,183 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2018-2022 Andre Richter -+ -+// Rust embedded logo for `make doc`. -+#![doc(html_logo_url = "https://git.io/JeGIp")] -+ -+//! 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(core_intrinsics)] -+#![feature(format_args_nl)] -+#![feature(linkage)] -+#![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 panic_wait; -+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; -+ -+//-------------------------------------------------------------------------------------------------- -+// 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::console::qemu_bring_up_console(); -+ -+ test_main(); -+ -+ cpu::qemu_exit_success() -+} - -diff -uNr 11_exceptions_part1_groundwork/src/main.rs 12_integrated_testing/src/main.rs ---- 11_exceptions_part1_groundwork/src/main.rs -+++ 12_integrated_testing/src/main.rs -@@ -6,123 +6,12 @@ - #![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 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(core_intrinsics)] -+ - #![feature(format_args_nl)] --#![feature(panic_info_message)] --#![feature(trait_alias)] - #![no_main] - #![no_std] - --mod bsp; --mod console; --mod cpu; --mod driver; --mod exception; --mod memory; --mod panic_wait; --mod print; --mod synchronization; --mod time; -+use libkernel::{bsp, console, driver, exception, info, memory, time}; - - /// Early init code. - /// -@@ -133,6 +22,7 @@ - /// - 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 driver::interface::DriverManager; - use memory::mmu::interface::MMU; -@@ -159,15 +49,9 @@ - fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; -- use core::time::Duration; - use driver::interface::DriverManager; -- use time::interface::TimeManager; - -- info!( -- "{} version {}", -- env!("CARGO_PKG_NAME"), -- env!("CARGO_PKG_VERSION") -- ); -+ info!("{}", libkernel::version()); - info!("Booting on: {}", bsp::board_name()); - - info!("MMU online. Special regions:"); -@@ -193,31 +77,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 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 11_exceptions_part1_groundwork/src/memory/mmu.rs 12_integrated_testing/src/memory/mmu.rs ---- 11_exceptions_part1_groundwork/src/memory/mmu.rs -+++ 12_integrated_testing/src/memory/mmu.rs -@@ -66,7 +66,6 @@ - - /// Architecture agnostic translation types. - #[allow(missing_docs)] --#[allow(dead_code)] - #[derive(Copy, Clone)] - pub enum Translation { - Identity, -@@ -261,4 +260,9 @@ - info!("{}", i); - } - } -+ -+ #[cfg(test)] -+ pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { -+ &self.inner -+ } - } - -diff -uNr 11_exceptions_part1_groundwork/src/panic_wait.rs 12_integrated_testing/src/panic_wait.rs ---- 11_exceptions_part1_groundwork/src/panic_wait.rs -+++ 12_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 `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() -+ } -+} -+ - /// Prints with a newline - only use from the panic handler. - /// - /// Carbon copy from -@@ -53,7 +70,7 @@ - return; - } - -- cpu::wait_forever() -+ _panic_exit() - } - - #[panic_handler] -@@ -81,5 +98,5 @@ - info.message().unwrap_or(&format_args!("")), - ); - -- cpu::wait_forever() -+ _panic_exit() - } - -diff -uNr 11_exceptions_part1_groundwork/test-macros/Cargo.toml 12_integrated_testing/test-macros/Cargo.toml ---- 11_exceptions_part1_groundwork/test-macros/Cargo.toml -+++ 12_integrated_testing/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 -uNr 11_exceptions_part1_groundwork/test-macros/src/lib.rs 12_integrated_testing/test-macros/src/lib.rs ---- 11_exceptions_part1_groundwork/test-macros/src/lib.rs -+++ 12_integrated_testing/test-macros/src/lib.rs -@@ -0,0 +1,29 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2022 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 11_exceptions_part1_groundwork/tests/00_console_sanity.rb 12_integrated_testing/tests/00_console_sanity.rb ---- 11_exceptions_part1_groundwork/tests/00_console_sanity.rb -+++ 12_integrated_testing/tests/00_console_sanity.rb -@@ -0,0 +1,48 @@ -+# frozen_string_literal: true -+ -+# SPDX-License-Identifier: MIT OR Apache-2.0 -+# -+# Copyright (c) 2019-2022 Andre Richter -+ -+require_relative '../../common/tests/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 -uNr 11_exceptions_part1_groundwork/tests/00_console_sanity.rs 12_integrated_testing/tests/00_console_sanity.rs ---- 11_exceptions_part1_groundwork/tests/00_console_sanity.rs -+++ 12_integrated_testing/tests/00_console_sanity.rs -@@ -0,0 +1,38 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2022 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 bsp::console::console; -+ use console::interface::*; -+ -+ exception::handling_init(); -+ bsp::console::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 -uNr 11_exceptions_part1_groundwork/tests/01_timer_sanity.rs 12_integrated_testing/tests/01_timer_sanity.rs ---- 11_exceptions_part1_groundwork/tests/01_timer_sanity.rs -+++ 12_integrated_testing/tests/01_timer_sanity.rs -@@ -0,0 +1,49 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2022 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, time::interface::TimeManager}; -+use test_macros::kernel_test; -+ -+#[no_mangle] -+unsafe fn kernel_init() -> ! { -+ exception::handling_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 11_exceptions_part1_groundwork/tests/02_exception_sync_page_fault.rs 12_integrated_testing/tests/02_exception_sync_page_fault.rs ---- 11_exceptions_part1_groundwork/tests/02_exception_sync_page_fault.rs -+++ 12_integrated_testing/tests/02_exception_sync_page_fault.rs -@@ -0,0 +1,43 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2022 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::console::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 -uNr 11_exceptions_part1_groundwork/tests/03_exception_restore_sanity.rb 12_integrated_testing/tests/03_exception_restore_sanity.rb ---- 11_exceptions_part1_groundwork/tests/03_exception_restore_sanity.rb -+++ 12_integrated_testing/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 Andre Richter -+ -+require_relative '../../common/tests/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 -uNr 11_exceptions_part1_groundwork/tests/03_exception_restore_sanity.rs 12_integrated_testing/tests/03_exception_restore_sanity.rs ---- 11_exceptions_part1_groundwork/tests/03_exception_restore_sanity.rs -+++ 12_integrated_testing/tests/03_exception_restore_sanity.rs -@@ -0,0 +1,55 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2022 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::console::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 -uNr 11_exceptions_part1_groundwork/tests/boot_test_string.rb 12_integrated_testing/tests/boot_test_string.rb ---- 11_exceptions_part1_groundwork/tests/boot_test_string.rb -+++ 12_integrated_testing/tests/boot_test_string.rb -@@ -1,3 +1,3 @@ - # frozen_string_literal: true - --EXPECTED_PRINT = 'lr : 0x' -+EXPECTED_PRINT = 'Echoing input now' - -diff -uNr 11_exceptions_part1_groundwork/tests/panic_exit_success/mod.rs 12_integrated_testing/tests/panic_exit_success/mod.rs ---- 11_exceptions_part1_groundwork/tests/panic_exit_success/mod.rs -+++ 12_integrated_testing/tests/panic_exit_success/mod.rs -@@ -0,0 +1,9 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2022 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 11_exceptions_part1_groundwork/tests/panic_wait_forever/mod.rs 12_integrated_testing/tests/panic_wait_forever/mod.rs ---- 11_exceptions_part1_groundwork/tests/panic_wait_forever/mod.rs -+++ 12_integrated_testing/tests/panic_wait_forever/mod.rs -@@ -0,0 +1,9 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2022 Andre Richter -+ -+/// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. -+#[no_mangle] -+fn _panic_exit() -> ! { -+ libkernel::cpu::wait_forever() -+} - -diff -uNr 11_exceptions_part1_groundwork/test-types/Cargo.toml 12_integrated_testing/test-types/Cargo.toml ---- 11_exceptions_part1_groundwork/test-types/Cargo.toml -+++ 12_integrated_testing/test-types/Cargo.toml -@@ -0,0 +1,5 @@ -+[package] -+name = "test-types" -+version = "0.1.0" -+authors = ["Andre Richter "] -+edition = "2021" - -diff -uNr 11_exceptions_part1_groundwork/test-types/src/lib.rs 12_integrated_testing/test-types/src/lib.rs ---- 11_exceptions_part1_groundwork/test-types/src/lib.rs -+++ 12_integrated_testing/test-types/src/lib.rs -@@ -0,0 +1,16 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2019-2022 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(), -+} +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 00000000..97dd972e --- /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/build.rs b/12_integrated_testing/kernel/build.rs similarity index 100% rename from 12_integrated_testing/build.rs rename to 12_integrated_testing/kernel/build.rs diff --git a/12_integrated_testing/src/_arch/aarch64/cpu.rs b/12_integrated_testing/kernel/src/_arch/aarch64/cpu.rs similarity index 93% rename from 12_integrated_testing/src/_arch/aarch64/cpu.rs rename to 12_integrated_testing/kernel/src/_arch/aarch64/cpu.rs index 66da661c..2d010473 100644 --- a/12_integrated_testing/src/_arch/aarch64/cpu.rs +++ b/12_integrated_testing/kernel/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.rs b/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.rs similarity index 92% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.rs rename to 12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.rs index f677c9c4..c80f3ebb 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.rs +++ b/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,12 +11,16 @@ //! //! crate::cpu::boot::arch_boot +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; -use cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Private Code diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/boot.s b/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.s similarity index 85% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/boot.s rename to 12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.s index 28b35087..f6df2123 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/boot.s +++ b/12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.s @@ -18,9 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _EL2, 0x8 -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -32,12 +29,12 @@ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL - cmp x0, _EL2 + 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, _core_id_mask + 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 @@ -60,6 +57,14 @@ _start: 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 diff --git a/12_integrated_testing/src/_arch/aarch64/exception.rs b/12_integrated_testing/kernel/src/_arch/aarch64/exception.rs similarity index 90% rename from 12_integrated_testing/src/_arch/aarch64/exception.rs rename to 12_integrated_testing/kernel/src/_arch/aarch64/exception.rs index e84699e1..4df4adab 100644 --- a/12_integrated_testing/src/_arch/aarch64/exception.rs +++ b/12_integrated_testing/kernel/src/_arch/aarch64/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! @@ -11,8 +11,8 @@ //! //! crate::exception::arch_exception +use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::InMemoryRegister, @@ -45,7 +45,7 @@ struct ExceptionContext { /// Saved program status. spsr_el1: SpsrEL1, - // Exception syndrome register. + /// Exception syndrome register. esr_el1: EsrEL1, } @@ -67,17 +67,17 @@ fn default_exception_handler(exc: &ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } @@ -86,7 +86,7 @@ unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { #[cfg(feature = "test_build")] { const TEST_SVC_ID: u64 = 0x1337; @@ -102,12 +102,12 @@ unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { } #[no_mangle] -unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { +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) { +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -116,17 +116,17 @@ unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -135,17 +135,17 @@ unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } diff --git a/12_integrated_testing/src/_arch/aarch64/exception.s b/12_integrated_testing/kernel/src/_arch/aarch64/exception.s similarity index 97% rename from 12_integrated_testing/src/_arch/aarch64/exception.s rename to 12_integrated_testing/kernel/src/_arch/aarch64/exception.s index 5aae30b9..91805ee7 100644 --- a/12_integrated_testing/src/_arch/aarch64/exception.s +++ b/12_integrated_testing/kernel/src/_arch/aarch64/exception.s @@ -9,6 +9,7 @@ /// 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 @@ -47,6 +48,9 @@ // 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 diff --git a/12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs b/12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs similarity index 95% rename from 12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs rename to 12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs index e3e3672e..65fcad25 100644 --- a/12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs +++ b/12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! @@ -11,7 +11,7 @@ //! //! crate::exception::asynchronous::arch_asynchronous -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- diff --git a/12_integrated_testing/src/_arch/aarch64/memory/mmu.rs b/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu.rs similarity index 98% rename from 12_integrated_testing/src/_arch/aarch64/memory/mmu.rs rename to 12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu.rs index 15a7faeb..99ecaa2b 100644 --- a/12_integrated_testing/src/_arch/aarch64/memory/mmu.rs +++ b/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! @@ -17,8 +17,8 @@ use crate::{ bsp, memory, memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, }; +use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu/translation_table.rs b/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs similarity index 99% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu/translation_table.rs rename to 12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs index 78776126..5e45a5fd 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu/translation_table.rs +++ b/12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! 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 00000000..ee1c3ef7 --- /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/src/bsp.rs b/12_integrated_testing/kernel/src/bsp.rs similarity index 81% rename from 12_integrated_testing/src/bsp.rs rename to 12_integrated_testing/kernel/src/bsp.rs index 824787f6..246973bc 100644 --- a/12_integrated_testing/src/bsp.rs +++ b/12_integrated_testing/kernel/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/12_integrated_testing/src/bsp/device_driver.rs b/12_integrated_testing/kernel/src/bsp/device_driver.rs similarity index 77% rename from 12_integrated_testing/src/bsp/device_driver.rs rename to 12_integrated_testing/kernel/src/bsp/device_driver.rs index 6e9bf8f3..64049a4c 100644 --- a/12_integrated_testing/src/bsp/device_driver.rs +++ b/12_integrated_testing/kernel/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/12_integrated_testing/src/bsp/device_driver/bcm.rs b/12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs similarity index 73% rename from 12_integrated_testing/src/bsp/device_driver/bcm.rs rename to 12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs index b4b7906e..1c343d1d 100644 --- a/12_integrated_testing/src/bsp/device_driver/bcm.rs +++ b/12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. diff --git a/12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs similarity index 93% rename from 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs rename to 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs index dbb4beaa..8e57dfed 100644 --- a/12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ b/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -143,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. @@ -189,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -214,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/12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs similarity index 96% rename from 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs rename to 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs index 878ea567..d92612ea 100644 --- a/12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ b/12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -326,7 +323,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -346,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> { @@ -364,7 +367,7 @@ 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)) } @@ -400,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/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/common.rs b/12_integrated_testing/kernel/src/bsp/device_driver/common.rs similarity index 94% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/common.rs rename to 12_integrated_testing/kernel/src/bsp/device_driver/common.rs index fd9e988e..dfe7d8ef 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/common.rs +++ b/12_integrated_testing/kernel/src/bsp/device_driver/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. diff --git a/12_integrated_testing/src/bsp/raspberrypi.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi.rs similarity index 50% rename from 12_integrated_testing/src/bsp/raspberrypi.rs rename to 12_integrated_testing/kernel/src/bsp/raspberrypi.rs index 22edb4fa..3ea864dc 100644 --- a/12_integrated_testing/src/bsp/raspberrypi.rs +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi.rs @@ -1,25 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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) }; - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/cpu.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi/cpu.rs similarity index 87% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/cpu.rs rename to 12_integrated_testing/kernel/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/cpu.rs +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. 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 00000000..7ecb48c8 --- /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/11_exceptions_part1_groundwork/src/bsp/raspberrypi/link.ld b/12_integrated_testing/kernel/src/bsp/raspberrypi/kernel.ld similarity index 88% rename from 11_exceptions_part1_groundwork/src/bsp/raspberrypi/link.ld rename to 12_integrated_testing/kernel/src/bsp/raspberrypi/kernel.ld index 2ce4b44b..6d939889 100644 --- a/11_exceptions_part1_groundwork/src/bsp/raspberrypi/link.ld +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/kernel.ld @@ -60,7 +60,6 @@ SECTIONS } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; @@ -78,4 +77,12 @@ SECTIONS . = 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/src/bsp/raspberrypi/memory.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs similarity index 98% rename from 12_integrated_testing/src/bsp/raspberrypi/memory.rs rename to 12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs index 7a57b618..661476f4 100644 --- a/12_integrated_testing/src/bsp/raspberrypi/memory.rs +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs b/12_integrated_testing/kernel/src/bsp/raspberrypi/memory/mmu.rs similarity index 98% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs rename to 12_integrated_testing/kernel/src/bsp/raspberrypi/memory/mmu.rs index f8cdc82f..563c8ba9 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs +++ b/12_integrated_testing/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. diff --git a/12_integrated_testing/kernel/src/common.rs b/12_integrated_testing/kernel/src/common.rs new file mode 100644 index 00000000..782a5da1 --- /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/src/console.rs b/12_integrated_testing/kernel/src/console.rs similarity index 53% rename from 12_integrated_testing/src/console.rs rename to 12_integrated_testing/kernel/src/console.rs index e49e241f..a83f86fe 100644 --- a/12_integrated_testing/src/console.rs +++ b/12_integrated_testing/kernel/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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/12_integrated_testing/kernel/src/console/null_console.rs b/12_integrated_testing/kernel/src/console/null_console.rs new file mode 100644 index 00000000..cbb7ec7d --- /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/src/cpu.rs b/12_integrated_testing/kernel/src/cpu.rs similarity index 89% rename from 12_integrated_testing/src/cpu.rs rename to 12_integrated_testing/kernel/src/cpu.rs index 6d3e9f08..1f6b57f3 100644 --- a/12_integrated_testing/src/cpu.rs +++ b/12_integrated_testing/kernel/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/12_integrated_testing/src/cpu/boot.rs b/12_integrated_testing/kernel/src/cpu/boot.rs similarity index 71% rename from 12_integrated_testing/src/cpu/boot.rs rename to 12_integrated_testing/kernel/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/12_integrated_testing/src/cpu/boot.rs +++ b/12_integrated_testing/kernel/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/12_integrated_testing/kernel/src/driver.rs b/12_integrated_testing/kernel/src/driver.rs new file mode 100644 index 00000000..050e7022 --- /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/14_virtual_mem_part2_mmio_remap/src/exception.rs b/12_integrated_testing/kernel/src/exception.rs similarity index 94% rename from 14_virtual_mem_part2_mmio_remap/src/exception.rs rename to 12_integrated_testing/kernel/src/exception.rs index f4af8144..3d5f219f 100644 --- a/14_virtual_mem_part2_mmio_remap/src/exception.rs +++ b/12_integrated_testing/kernel/src/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. @@ -21,7 +21,7 @@ pub use arch_exception::{current_privilege_level, handling_init}; /// Kernel privilege levels. #[allow(missing_docs)] -#[derive(PartialEq)] +#[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, diff --git a/12_integrated_testing/src/exception/asynchronous.rs b/12_integrated_testing/kernel/src/exception/asynchronous.rs similarity index 88% rename from 12_integrated_testing/src/exception/asynchronous.rs rename to 12_integrated_testing/kernel/src/exception/asynchronous.rs index bad85779..fd059326 100644 --- a/12_integrated_testing/src/exception/asynchronous.rs +++ b/12_integrated_testing/kernel/src/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Asynchronous exception handling. diff --git a/14_virtual_mem_part2_mmio_remap/src/lib.rs b/12_integrated_testing/kernel/src/lib.rs similarity index 95% rename from 14_virtual_mem_part2_mmio_remap/src/lib.rs rename to 12_integrated_testing/kernel/src/lib.rs index 9ed0941c..16e0b1d0 100644 --- a/14_virtual_mem_part2_mmio_remap/src/lib.rs +++ b/12_integrated_testing/kernel/src/lib.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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` library. //! @@ -109,13 +111,15 @@ #![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(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)] @@ -134,7 +138,6 @@ pub mod driver; pub mod exception; pub mod memory; pub mod print; -pub mod state; pub mod time; //-------------------------------------------------------------------------------------------------- @@ -180,8 +183,7 @@ pub fn test_runner(tests: &[&test_types::UnitTest]) { #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); test_main(); diff --git a/12_integrated_testing/src/main.rs b/12_integrated_testing/kernel/src/main.rs similarity index 69% rename from 12_integrated_testing/src/main.rs rename to 12_integrated_testing/kernel/src/main.rs index 2c1bf9ac..9a8df1d7 100644 --- a/12_integrated_testing/src/main.rs +++ b/12_integrated_testing/kernel/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. @@ -24,7 +26,6 @@ use libkernel::{bsp, console, driver, exception, info, memory, time}; /// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; use memory::mmu::interface::MMU; exception::handling_init(); @@ -33,12 +34,13 @@ unsafe fn kernel_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); - } + // 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. @@ -47,9 +49,7 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { - use bsp::console::console; - use console::interface::All; - use driver::interface::DriverManager; + use console::console; info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); @@ -69,20 +69,14 @@ fn kernel_main() -> ! { ); info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); info!("Echoing input now"); // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { - let c = bsp::console::console().read_char(); - bsp::console::console().write_char(c); + let c = console().read_char(); + console().write_char(c); } } diff --git a/12_integrated_testing/src/memory.rs b/12_integrated_testing/kernel/src/memory.rs similarity index 58% rename from 12_integrated_testing/src/memory.rs rename to 12_integrated_testing/kernel/src/memory.rs index ac6663b3..6dd8f186 100644 --- a/12_integrated_testing/src/memory.rs +++ b/12_integrated_testing/kernel/src/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management. diff --git a/13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs b/12_integrated_testing/kernel/src/memory/mmu.rs similarity index 94% rename from 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs rename to 12_integrated_testing/kernel/src/memory/mmu.rs index a68973e7..7c7fc397 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs +++ b/12_integrated_testing/kernel/src/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. //! @@ -20,6 +20,7 @@ mod arch_mmu; mod translation_table; +use crate::common; use core::{fmt, ops::RangeInclusive}; //-------------------------------------------------------------------------------------------------- @@ -178,19 +179,7 @@ impl fmt::Display for TranslationDescriptor { 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 (size, unit) = common::size_human_readable_ceil(size); let attr = match self.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", diff --git a/13_exceptions_part2_peripheral_IRQs/src/memory/mmu/translation_table.rs b/12_integrated_testing/kernel/src/memory/mmu/translation_table.rs similarity index 88% rename from 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/translation_table.rs rename to 12_integrated_testing/kernel/src/memory/mmu/translation_table.rs index 88e3fe48..1a2581aa 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/memory/mmu/translation_table.rs +++ b/12_integrated_testing/kernel/src/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Translation table. 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 00000000..a896ad5e --- /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/15_virtual_mem_part3_precomputed_tables/src/print.rs b/12_integrated_testing/kernel/src/print.rs similarity index 85% rename from 15_virtual_mem_part3_precomputed_tables/src/print.rs rename to 12_integrated_testing/kernel/src/print.rs index 9ec13a28..8e303046 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/print.rs +++ b/12_integrated_testing/kernel/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/12_integrated_testing/src/synchronization.rs b/12_integrated_testing/kernel/src/synchronization.rs similarity index 91% rename from 12_integrated_testing/src/synchronization.rs rename to 12_integrated_testing/kernel/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/12_integrated_testing/src/synchronization.rs +++ b/12_integrated_testing/kernel/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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/12_integrated_testing/kernel/src/time.rs b/12_integrated_testing/kernel/src/time.rs new file mode 100644 index 00000000..a9d50120 --- /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/tests/00_console_sanity.rb b/12_integrated_testing/kernel/tests/00_console_sanity.rb similarity index 81% rename from 12_integrated_testing/tests/00_console_sanity.rb rename to 12_integrated_testing/kernel/tests/00_console_sanity.rb index 48c9703d..8be7a2f1 100644 --- a/12_integrated_testing/tests/00_console_sanity.rb +++ b/12_integrated_testing/kernel/tests/00_console_sanity.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2019-2022 Andre Richter +# Copyright (c) 2019-2023 Andre Richter -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify sending and receiving works as expected. class TxRxHandshakeTest < SubtestBase @@ -40,9 +40,9 @@ class RxStatisticsTest < SubtestBase end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Test registration -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- def subtest_collection [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] end diff --git a/13_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rs b/12_integrated_testing/kernel/tests/00_console_sanity.rs similarity index 82% rename from 13_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rs rename to 12_integrated_testing/kernel/tests/00_console_sanity.rs index dccb6cc2..982c6170 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rs +++ b/12_integrated_testing/kernel/tests/00_console_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Console sanity tests - RX, TX and statistics. @@ -15,11 +15,10 @@ use libkernel::{bsp, console, cpu, exception, print}; #[no_mangle] unsafe fn kernel_init() -> ! { - use bsp::console::console; - use console::interface::*; + use console::console; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); diff --git a/13_exceptions_part2_peripheral_IRQs/tests/01_timer_sanity.rs b/12_integrated_testing/kernel/tests/01_timer_sanity.rs similarity index 83% rename from 13_exceptions_part2_peripheral_IRQs/tests/01_timer_sanity.rs rename to 12_integrated_testing/kernel/tests/01_timer_sanity.rs index 59ef4a7f..3b065f13 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/01_timer_sanity.rs +++ b/12_integrated_testing/kernel/tests/01_timer_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Timer sanity tests. @@ -11,13 +11,13 @@ #![test_runner(libkernel::test_runner)] use core::time::Duration; -use libkernel::{bsp, cpu, exception, time, time::interface::TimeManager}; +use libkernel::{bsp, cpu, exception, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. @@ -35,6 +35,7 @@ fn timer_is_counting() { /// 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) } diff --git a/12_integrated_testing/tests/02_exception_sync_page_fault.rs b/12_integrated_testing/kernel/tests/02_exception_sync_page_fault.rs similarity index 92% rename from 12_integrated_testing/tests/02_exception_sync_page_fault.rs rename to 12_integrated_testing/kernel/tests/02_exception_sync_page_fault.rs index 9be94acd..bf5b7d71 100644 --- a/12_integrated_testing/tests/02_exception_sync_page_fault.rs +++ b/12_integrated_testing/kernel/tests/02_exception_sync_page_fault.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. @@ -24,7 +24,7 @@ unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + 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"); diff --git a/14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rb b/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rb similarity index 65% rename from 14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rb rename to 12_integrated_testing/kernel/tests/03_exception_restore_sanity.rb index c3c725ed..02f51f74 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rb +++ b/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2022 Andre Richter +# Copyright (c) 2022-2023 Andre Richter -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify that exception restore works. class ExceptionRestoreTest < SubtestBase @@ -17,9 +17,9 @@ class ExceptionRestoreTest < SubtestBase end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Test registration -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- def subtest_collection [ExceptionRestoreTest.new] end diff --git a/13_exceptions_part2_peripheral_IRQs/tests/03_exception_restore_sanity.rs b/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rs similarity index 92% rename from 13_exceptions_part2_peripheral_IRQs/tests/03_exception_restore_sanity.rs rename to 12_integrated_testing/kernel/tests/03_exception_restore_sanity.rs index f25ed645..e22f4977 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/03_exception_restore_sanity.rs +++ b/12_integrated_testing/kernel/tests/03_exception_restore_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter //! A simple sanity test to see if exception restore code works. @@ -33,7 +33,7 @@ unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); diff --git a/12_integrated_testing/tests/boot_test_string.rb b/12_integrated_testing/kernel/tests/boot_test_string.rb similarity index 100% rename from 12_integrated_testing/tests/boot_test_string.rb rename to 12_integrated_testing/kernel/tests/boot_test_string.rb diff --git a/14_virtual_mem_part2_mmio_remap/tests/panic_exit_success/mod.rs b/12_integrated_testing/kernel/tests/panic_exit_success/mod.rs similarity index 77% rename from 14_virtual_mem_part2_mmio_remap/tests/panic_exit_success/mod.rs rename to 12_integrated_testing/kernel/tests/panic_exit_success/mod.rs index 908fac51..449ad6f9 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/panic_exit_success/mod.rs +++ b/12_integrated_testing/kernel/tests/panic_exit_success/mod.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter /// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. #[no_mangle] diff --git a/12_integrated_testing/tests/panic_wait_forever/mod.rs b/12_integrated_testing/kernel/tests/panic_wait_forever/mod.rs similarity index 74% rename from 12_integrated_testing/tests/panic_wait_forever/mod.rs rename to 12_integrated_testing/kernel/tests/panic_wait_forever/mod.rs index 7a4effa5..9ac19144 100644 --- a/12_integrated_testing/tests/panic_wait_forever/mod.rs +++ b/12_integrated_testing/kernel/tests/panic_wait_forever/mod.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter /// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. #[no_mangle] diff --git a/12_integrated_testing/test-macros/Cargo.toml b/12_integrated_testing/libraries/test-macros/Cargo.toml similarity index 100% rename from 12_integrated_testing/test-macros/Cargo.toml rename to 12_integrated_testing/libraries/test-macros/Cargo.toml diff --git a/12_integrated_testing/test-macros/src/lib.rs b/12_integrated_testing/libraries/test-macros/src/lib.rs similarity index 85% rename from 12_integrated_testing/test-macros/src/lib.rs rename to 12_integrated_testing/libraries/test-macros/src/lib.rs index 83025a09..52cf893d 100644 --- a/12_integrated_testing/test-macros/src/lib.rs +++ b/12_integrated_testing/libraries/test-macros/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter use proc_macro::TokenStream; use proc_macro2::Span; @@ -11,7 +11,7 @@ use syn::{parse_macro_input, Ident, ItemFn}; 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_name = &format!("{}", f.sig.ident); let test_ident = Ident::new( &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), Span::call_site(), diff --git a/12_integrated_testing/test-types/Cargo.toml b/12_integrated_testing/libraries/test-types/Cargo.toml similarity index 100% rename from 12_integrated_testing/test-types/Cargo.toml rename to 12_integrated_testing/libraries/test-types/Cargo.toml diff --git a/14_virtual_mem_part2_mmio_remap/test-types/src/lib.rs b/12_integrated_testing/libraries/test-types/src/lib.rs similarity index 82% rename from 14_virtual_mem_part2_mmio_remap/test-types/src/lib.rs rename to 12_integrated_testing/libraries/test-types/src/lib.rs index 922c2a1c..38961a9c 100644 --- a/14_virtual_mem_part2_mmio_remap/test-types/src/lib.rs +++ b/12_integrated_testing/libraries/test-types/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Types for the `custom_test_frameworks` implementation. diff --git a/12_integrated_testing/src/_arch/aarch64/time.rs b/12_integrated_testing/src/_arch/aarch64/time.rs deleted file mode 100644 index c814219c..00000000 --- a/12_integrated_testing/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } -} - -//-------------------------------------------------------------------------------------------------- -// 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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; - - 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) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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_integrated_testing/src/bsp/device_driver/common.rs b/12_integrated_testing/src/bsp/device_driver/common.rs deleted file mode 100644 index fd9e988e..00000000 --- a/12_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-2022 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/src/bsp/raspberrypi/console.rs b/12_integrated_testing/src/bsp/raspberrypi/console.rs deleted file mode 100644 index eaef0b1f..00000000 --- a/12_integrated_testing/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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. -#[cfg(feature = "test_build")] -pub fn qemu_bring_up_console() {} diff --git a/12_integrated_testing/src/bsp/raspberrypi/driver.rs b/12_integrated_testing/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index b5538baa..00000000 --- a/12_integrated_testing/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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_integrated_testing/src/driver.rs b/12_integrated_testing/src/driver.rs deleted file mode 100644 index 2fcc7562..00000000 --- a/12_integrated_testing/src/driver.rs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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_integrated_testing/src/lib.rs b/12_integrated_testing/src/lib.rs deleted file mode 100644 index 51f10d7c..00000000 --- a/12_integrated_testing/src/lib.rs +++ /dev/null @@ -1,183 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 Andre Richter - -// Rust embedded logo for `make doc`. -#![doc(html_logo_url = "https://git.io/JeGIp")] - -//! 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(core_intrinsics)] -#![feature(format_args_nl)] -#![feature(linkage)] -#![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 panic_wait; -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; - -//-------------------------------------------------------------------------------------------------- -// 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::console::qemu_bring_up_console(); - - test_main(); - - cpu::qemu_exit_success() -} diff --git a/12_integrated_testing/src/time.rs b/12_integrated_testing/src/time.rs deleted file mode 100644 index 6d92b196..00000000 --- a/12_integrated_testing/src/time.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020-2022 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; - -//-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports -//-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - 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_exceptions_part2_peripheral_IRQs/.vscode/settings.json b/13_exceptions_part2_peripheral_IRQs/.vscode/settings.json index 0a8d7c09..9ef30cd0 100644 --- a/13_exceptions_part2_peripheral_IRQs/.vscode/settings.json +++ b/13_exceptions_part2_peripheral_IRQs/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index ba1b9013..ad1e8660 100644 --- a/13_exceptions_part2_peripheral_IRQs/Cargo.lock +++ b/13_exceptions_part2_peripheral_IRQs/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,8 +15,7 @@ dependencies = [ name = "mingo" version = "0.13.0" dependencies = [ - "cortex-a", - "mingo", + "aarch64-cpu", "qemu-exit", "test-macros", "test-types", @@ -25,11 +24,11 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.37" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" dependencies = [ - "unicode-xid", + "unicode-ident", ] [[package]] @@ -40,22 +39,22 @@ checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" [[package]] name = "quote" -version = "1.0.17" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "syn" -version = "1.0.91" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" dependencies = [ "proc-macro2", "quote", - "unicode-xid", + "unicode-ident", ] [[package]] @@ -74,12 +73,12 @@ version = "0.1.0" [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" [[package]] -name = "unicode-xid" -version = "0.2.2" +name = "unicode-ident" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/13_exceptions_part2_peripheral_IRQs/Cargo.toml b/13_exceptions_part2_peripheral_IRQs/Cargo.toml index a1a3bfbf..6480a727 100644 --- a/13_exceptions_part2_peripheral_IRQs/Cargo.toml +++ b/13_exceptions_part2_peripheral_IRQs/Cargo.toml @@ -1,67 +1,9 @@ -[package] -name = "mingo" -version = "0.13.0" -authors = ["Andre Richter "] -edition = "2021" +[workspace] + +members = [ + "libraries/*", + "kernel" +] [profile.release] lto = true - -[features] -default = [] -bsp_rpi3 = ["tock-registers"] -bsp_rpi4 = ["tock-registers"] -test_build = ["qemu-exit"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] -test-types = { path = "test-types" } - -# Optional dependencies -tock-registers = { version = "0.7.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] -cortex-a = { version = "7.x.x" } - -##-------------------------------------------------------------------------------------------------- -## Testing -##-------------------------------------------------------------------------------------------------- - -[dev-dependencies] -test-macros = { path = "test-macros" } - -# The following line is a workaround, as suggested in [1], to enable a feature in test-builds only. -# This allows building the library part of the kernel with specialized code for testing. -# -# -# [1] https://github.com/rust-lang/cargo/issues/2911#issuecomment-749580481 -mingo = { path = ".", features = ["test_build"] } - -# 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/Makefile b/13_exceptions_part2_peripheral_IRQs/Makefile index afa22480..4e2efeff 100644 --- a/13_exceptions_part2_peripheral_IRQs/Makefile +++ b/13_exceptions_part2_peripheral_IRQs/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -41,7 +42,7 @@ ifeq ($(BSP),rpi3) 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 + 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 @@ -55,7 +56,7 @@ else ifeq ($(BSP),rpi4) 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 + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif @@ -67,14 +68,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -94,11 +95,10 @@ COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -TEST_CMD = cargo test $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary @@ -167,7 +167,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -203,6 +203,8 @@ chainboot: $(KERNEL_BIN) ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean @@ -225,7 +227,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -235,12 +236,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- @@ -277,6 +272,8 @@ gdb gdb-opt0: $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- .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: @@ -295,7 +292,11 @@ test_boot: $(KERNEL_BIN) ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER - #!/usr/bin/env bash +#!/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') diff --git a/13_exceptions_part2_peripheral_IRQs/README.md b/13_exceptions_part2_peripheral_IRQs/README.md index eefe4b7e..5be65914 100644 --- a/13_exceptions_part2_peripheral_IRQs/README.md +++ b/13_exceptions_part2_peripheral_IRQs/README.md @@ -29,7 +29,6 @@ + [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) @@ -111,17 +110,16 @@ The trait is defined as `exception::asynchronous::interface::IRQManager`: ```rust pub trait IRQManager { /// The IRQ number type depends on the implementation. - type IRQNumberType; + type IRQNumberType: Copy; /// Register a handler. fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: super::IRQDescriptor, + irq_handler_descriptor: super::IRQHandlerDescriptor, ) -> Result<(), &'static str>; /// Enable an interrupt in the controller. - fn enable(&self, irq_number: Self::IRQNumberType); + fn enable(&self, irq_number: &Self::IRQNumberType); /// Handle pending interrupts. /// @@ -137,7 +135,7 @@ pub trait IRQManager { ); /// Print list of registered handlers. - fn print_handler(&self); + fn print_handler(&self) {} } ``` @@ -176,22 +174,21 @@ sufficient to uniquely encode the IRQs, because their ranges overlap. In the dri 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 }>; +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`]. +/// 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 `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`). +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 @@ -207,7 +204,7 @@ 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 }>; +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; ``` #### Registering IRQ Handlers @@ -265,35 +262,41 @@ respective drivers themselves. Therefore, we added a new function to the standar 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. +/// 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) -> Result<(), &'static str> { - Ok(()) +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) -> Result<(), &'static str> { - use bsp::exception::asynchronous::irq_manager; - use exception::asynchronous::{interface::IRQManager, IRQDescriptor}; +fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, +) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; - let descriptor = IRQDescriptor { - name: "BCM PL011 UART", - handler: self, - }; + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); - irq_manager().register_handler(self.irq_number, descriptor)?; - irq_manager().enable(self.irq_number); + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); Ok(()) } ``` -The `bsp::exception::asynchronous::irq_manager()` function used here returns a reference to an +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 @@ -302,33 +305,57 @@ later. The gist here is that the calls on `irq_manager()` will make the platform 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 +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. Therefore, we extend the instantiation of the `UART` driver accordingly, so that -the `BSP` now additionally provides the IRQ number as an argument: +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 -static PL011_UART: device_driver::PL011Uart = unsafe { - device_driver::PL011Uart::new( - memory::map::mmio::PL011_UART_BASE, - exception::asynchronous::irq_map::PL011_UART, - ) -}; +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 + ); + } + } + }); +} ``` -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: + +In `main.rs`, IRQs are unmasked right afterwards, after which point 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); - } -} +// Initialize all device drivers. +driver::driver_manager().init_drivers_and_irqs(); // Unmask interrupts on the boot CPU core. exception::asynchronous::local_irq_unmask(); @@ -369,11 +396,9 @@ the the implementation of the trait's handling function: ```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); +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); } ``` @@ -425,13 +450,9 @@ core are masked before the `f(data)` is being executed, and restored afterwards: /// 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); - } + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); ret } @@ -489,7 +510,7 @@ 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 source of the **peripheral** controller]: kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ##### The IRQ Handler Table @@ -497,8 +518,8 @@ Calls to `register_handler()` result in the driver inserting the provided handle specific table (the handler reference is a member of `IRQDescriptor`): ```rust -type HandlerTable = - [Option; InterruptController::NUM_PERIPHERAL_IRQS]; +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; ``` One of the requirements for safe operation of the `kernel` is that those handlers are not @@ -555,6 +576,10 @@ only call is happening before the transition from `kernel_init()` to `kernel_mai 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 @@ -617,9 +642,9 @@ register_structs! { (0x004 => TYPER: ReadOnly), (0x008 => _reserved1), (0x104 => ISENABLER: [ReadWrite; 31]), - (0x108 => _reserved2), + (0x180 => _reserved2), (0x820 => ITARGETSR: [ReadWrite; 248]), - (0x824 => @END), + (0xC00 => @END), } } @@ -630,7 +655,7 @@ register_structs! { (0x100 => ISENABLER: ReadWrite), (0x104 => _reserved2), (0x800 => ITARGETSR: [ReadOnly; 8]), - (0x804 => @END), + (0x820 => @END), } } ``` @@ -639,7 +664,7 @@ As with the implementation of the BCM interrupt controller driver, we won't cove parts in exhaustive detail. For that, please refer to [this folder] folder which contains all the sources. -[this folder]: src/bsp/device_driver/arm +[this folder]: kernel/src/bsp/device_driver/arm ## Test it @@ -667,6 +692,7 @@ Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now + __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | @@ -678,26 +704,26 @@ Minipush 1.0 [MP] ⏩ Pushing 66 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now -[ 1.010579] mingo version 0.13.0 -[ 1.010787] Booting on: Raspberry Pi 3 -[ 1.011242] MMU online. Special regions: -[ 1.011718] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data -[ 1.012737] 0x3f000000 - 0x4000ffff | 16 MiB | Dev RW PXN | Device MMIO -[ 1.013625] Current privilege level: EL1 -[ 1.014102] Exception handling state: -[ 1.014546] Debug: Masked -[ 1.014936] SError: Masked -[ 1.015326] IRQ: Unmasked -[ 1.015738] FIQ: Masked -[ 1.016127] Architectural timer resolution: 52 ns -[ 1.016702] Drivers loaded: -[ 1.017038] 1. BCM GPIO -[ 1.017395] 2. BCM PL011 UART -[ 1.017817] 3. BCM Interrupt Controller -[ 1.018348] Registered IRQ handlers: -[ 1.018782] Peripheral handler: -[ 1.019228] 57. BCM PL011 UART -[ 1.019735] Echoing input 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: @@ -710,6 +736,7 @@ Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now + __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | @@ -721,34 +748,34 @@ Minipush 1.0 [MP] ⏩ Pushing 73 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now -[ 1.030536] mingo version 0.13.0 -[ 1.030569] Booting on: Raspberry Pi 4 -[ 1.031024] MMU online. Special regions: -[ 1.031501] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data -[ 1.032519] 0xfe000000 - 0xff84ffff | 24 MiB | Dev RW PXN | Device MMIO -[ 1.033408] Current privilege level: EL1 -[ 1.033884] Exception handling state: -[ 1.034328] Debug: Masked -[ 1.034718] SError: Masked -[ 1.035108] IRQ: Unmasked -[ 1.035520] FIQ: Masked -[ 1.035910] Architectural timer resolution: 18 ns -[ 1.036484] Drivers loaded: -[ 1.036820] 1. BCM GPIO -[ 1.037178] 2. BCM PL011 UART -[ 1.037600] 3. GICv2 (ARM Generic Interrupt Controller v2) -[ 1.038337] Registered IRQ handlers: -[ 1.038770] Peripheral handler: -[ 1.039217] 153. BCM PL011 UART -[ 1.039725] Echoing input 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/Cargo.toml 13_exceptions_part2_peripheral_IRQs/Cargo.toml ---- 12_integrated_testing/Cargo.toml -+++ 13_exceptions_part2_peripheral_IRQs/Cargo.toml +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" @@ -758,13 +785,13 @@ diff -uNr 12_integrated_testing/Cargo.toml 13_exceptions_part2_peripheral_IRQs/C edition = "2021" -diff -uNr 12_integrated_testing/src/_arch/aarch64/cpu/smp.rs 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/smp.rs ---- 12_integrated_testing/src/_arch/aarch64/cpu/smp.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/smp.rs +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-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! @@ -775,7 +802,7 @@ diff -uNr 12_integrated_testing/src/_arch/aarch64/cpu/smp.rs 13_exceptions_part2 +//! +//! crate::cpu::smp::arch_smp + -+use cortex_a::registers::*; ++use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- @@ -793,16 +820,15 @@ diff -uNr 12_integrated_testing/src/_arch/aarch64/cpu/smp.rs 13_exceptions_part2 + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} -diff -uNr 12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs ---- 12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs -@@ -11,13 +11,18 @@ - //! +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 core::arch::asm; - use cortex_a::registers::*; + use aarch64_cpu::registers::*; -use tock_registers::interfaces::Readable; ++use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; //-------------------------------------------------------------------------------------------------- @@ -816,7 +842,7 @@ diff -uNr 12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs 13_e trait DaifField { fn daif_field() -> tock_registers::fields::Field; } -@@ -66,6 +71,71 @@ +@@ -66,6 +71,60 @@ // Public Code //-------------------------------------------------------------------------------------------------- @@ -832,42 +858,32 @@ diff -uNr 12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs 13_e +/// +/// "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) -+ ); ++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. -+/// -+/// # 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) -+ ); ++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). -+/// -+/// # Safety -+/// -+/// - Changes the HW state of the executing core. +#[inline(always)] -+pub unsafe fn local_irq_mask_save() -> u64 { ++pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + @@ -876,12 +892,11 @@ diff -uNr 12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs 13_e + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// -+/// # Safety ++/// # Invariant +/// -+/// - Changes the HW state of the executing core. +/// - No sanity checks on the input. +#[inline(always)] -+pub unsafe fn local_irq_restore(saved: u64) { ++pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + @@ -889,39 +904,37 @@ diff -uNr 12_integrated_testing/src/_arch/aarch64/exception/asynchronous.rs 13_e #[rustfmt::skip] pub fn print_state() { -diff -uNr 12_integrated_testing/src/_arch/aarch64/exception.rs 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs ---- 12_integrated_testing/src/_arch/aarch64/exception.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs +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::{bsp, exception}; ++use crate::exception; + use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; - use cortex_a::{asm::barrier, registers::*}; use tock_registers::{ -@@ -102,8 +103,11 @@ +@@ -102,8 +103,9 @@ } #[no_mangle] --unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { +-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); ++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/src/bsp/device_driver/arm/gicv2/gicc.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs ---- 12_integrated_testing/src/bsp/device_driver/arm/gicv2/gicc.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + @@ -1061,13 +1074,13 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2/gicc.rs 13_excep + } +} -diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2/gicd.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs ---- 12_integrated_testing/src/bsp/device_driver/arm/gicv2/gicd.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! @@ -1117,9 +1130,9 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2/gicd.rs 13_excep + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), -+ (0x108 => _reserved2), ++ (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), -+ (0x824 => @END), ++ (0xC00 => @END), + } +} + @@ -1130,7 +1143,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2/gicd.rs 13_excep + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), -+ (0x804 => @END), ++ (0x820 => @END), + } +} + @@ -1237,7 +1250,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2/gicd.rs 13_excep + } + + /// Enable an interrupt. -+ pub fn enable(&self, irq_num: super::IRQNumber) { ++ 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 @@ -1265,13 +1278,13 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2/gicd.rs 13_excep + } +} -diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs ---- 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs -@@ -0,0 +1,219 @@ +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! @@ -1350,20 +1363,25 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 13_exceptions +mod gicc; +mod gicd; + -+use crate::{bsp, cpu, driver, exception, synchronization, synchronization::InitStateLock}; ++use crate::{ ++ bsp::{self, device_driver::common::BoundedUsize}, ++ cpu, driver, exception, synchronization, ++ synchronization::InitStateLock, ++}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + -+type HandlerTable = [Option; GICv2::NUM_IRQS]; ++type HandlerTable = [Option>; ++ IRQNumber::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -+pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; ++pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { @@ -1383,7 +1401,8 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 13_exceptions + +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; ++ ++ pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// @@ -1394,7 +1413,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 13_exceptions + 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]), ++ handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), + } + } +} @@ -1405,8 +1424,10 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 13_exceptions +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { ++ type IRQNumberType = IRQNumber; ++ + fn compatible(&self) -> &'static str { -+ "GICv2 (ARM Generic Interrupt Controller v2)" ++ Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { @@ -1426,23 +1447,22 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 13_exceptions + + fn register_handler( + &self, -+ irq_number: Self::IRQNumberType, -+ descriptor: exception::asynchronous::IRQDescriptor, ++ irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { -+ let irq_number = irq_number.get(); ++ let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + -+ table[irq_number] = Some(descriptor); ++ table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + -+ fn enable(&self, irq_number: Self::IRQNumberType) { ++ fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + @@ -1465,7 +1485,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 13_exceptions + 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"); ++ descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); @@ -1482,20 +1502,20 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm/gicv2.rs 13_exceptions + 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); ++ info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} -diff -uNr 12_integrated_testing/src/bsp/device_driver/arm.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs ---- 12_integrated_testing/src/bsp/device_driver/arm.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + @@ -1503,19 +1523,21 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/arm.rs 13_exceptions_part2 + +pub use gicv2::*; -diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ---- 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -@@ -6,7 +6,7 @@ +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, +- bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, -+ synchronization::IRQSafeNullLock, ++ bsp::device_driver::common::MMIODerefWrapper, driver, exception::asynchronous::IRQNumber, ++ synchronization, synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, -@@ -121,7 +121,7 @@ +@@ -118,7 +118,7 @@ /// Representation of the GPIO HW. pub struct GPIO { @@ -1524,7 +1546,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 13_exc } //-------------------------------------------------------------------------------------------------- -@@ -197,7 +197,7 @@ +@@ -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 { @@ -1533,18 +1555,31 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 13_exc } } +@@ -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/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ---- 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs -@@ -0,0 +1,167 @@ +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. ++//! ++//! # Resources ++//! ++//! - + -+use super::{InterruptController, PendingIRQs, PeripheralIRQ}; ++use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, synchronization, @@ -1566,7 +1601,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), -+ (0x24 => @END), ++ (0x18 => @END), + } +} + @@ -1586,8 +1621,8 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + -+type HandlerTable = -+ [Option; InterruptController::NUM_PERIPHERAL_IRQS]; ++type HandlerTable = [Option>; ++ PeripheralIRQ::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions @@ -1619,7 +1654,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont + 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]), ++ handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), + } + } + @@ -1642,23 +1677,22 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont + + fn register_handler( + &self, -+ irq: Self::IRQNumberType, -+ descriptor: exception::asynchronous::IRQDescriptor, ++ irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { -+ let irq_number = irq.get(); ++ let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + -+ table[irq_number] = Some(descriptor); ++ table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + -+ fn enable(&self, irq: Self::IRQNumberType) { ++ fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 @@ -1684,7 +1718,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont + 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"); ++ descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } @@ -1699,26 +1733,31 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { -+ info!(" {: >3}. {}", i, handler.name); ++ info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} -diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ---- 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs -@@ -0,0 +1,131 @@ +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + -+use crate::{driver, exception}; ++use crate::{ ++ bsp::device_driver::common::BoundedUsize, ++ driver, ++ exception::{self, asynchronous::IRQHandlerDescriptor}, ++}; ++use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions @@ -1733,13 +1772,12 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont +// Public Definitions +//-------------------------------------------------------------------------------------------------- + -+pub type LocalIRQ = -+ exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -+pub type PeripheralIRQ = -+ exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; ++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), @@ -1764,16 +1802,13 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont + type Item = usize; + + fn next(&mut self) -> Option { -+ use core::intrinsics::cttz; -+ -+ let next = cttz(self.bitmask); -+ if next == 64 { ++ if self.bitmask == 0 { + return None; + } + -+ self.bitmask &= !(1 << next); -+ -+ Some(next as usize) ++ let next = self.bitmask.trailing_zeros() as usize; ++ self.bitmask &= self.bitmask.wrapping_sub(1); ++ Some(next) + } +} + @@ -1781,17 +1816,28 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont +// 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 { -+ const MAX_LOCAL_IRQ_NUMBER: usize = 11; ++ // 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; -+ const NUM_PERIPHERAL_IRQS: usize = Self::MAX_PERIPHERAL_IRQ_NUMBER + 1; ++ ++ 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: usize, periph_mmio_start_addr: usize) -> Self { ++ pub const unsafe fn new(periph_mmio_start_addr: usize) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } @@ -1803,8 +1849,10 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { ++ type IRQNumberType = IRQNumber; ++ + fn compatible(&self) -> &'static str { -+ "BCM Interrupt Controller" ++ Self::COMPATIBLE + } +} + @@ -1813,16 +1861,23 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont + + fn register_handler( + &self, -+ irq: Self::IRQNumberType, -+ descriptor: exception::asynchronous::IRQDescriptor, ++ irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { -+ match irq { ++ match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), -+ IRQNumber::Peripheral(pirq) => self.periph.register_handler(pirq, 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) { ++ fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), @@ -1842,21 +1897,24 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_interrupt_cont + } +} -diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ---- 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -@@ -10,8 +10,8 @@ +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, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, -+ synchronization, synchronization::IRQSafeNullLock, ++ bsp::device_driver::common::MMIODerefWrapper, ++ console, cpu, driver, ++ exception::{self, asynchronous::IRQNumber}, ++ synchronization, ++ synchronization::IRQSafeNullLock, }; use core::fmt; use tock_registers::{ -@@ -134,6 +134,52 @@ +@@ -134,6 +137,52 @@ ] ], @@ -1909,7 +1967,7 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. -@@ -152,7 +198,10 @@ +@@ -152,7 +201,10 @@ (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), @@ -1921,17 +1979,16 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs (0x44 => ICR: WriteOnly), (0x48 => @END), } -@@ -182,7 +231,8 @@ +@@ -179,7 +231,7 @@ /// Representation of the UART. pub struct PL011Uart { - inner: NullLock, + inner: IRQSafeNullLock, -+ irq_number: bsp::device_driver::IRQNumber, } //-------------------------------------------------------------------------------------------------- -@@ -250,6 +300,14 @@ +@@ -247,6 +299,14 @@ .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); @@ -1946,48 +2003,49 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs // Turn the UART on. self.registers .CR -@@ -332,9 +390,13 @@ - /// # Safety - /// +@@ -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 { -+ pub const unsafe fn new( -+ mmio_start_addr: usize, -+ irq_number: bsp::device_driver::IRQNumber, -+ ) -> Self { + 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)), -+ irq_number, } } } -@@ -354,6 +416,21 @@ +@@ -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) -> Result<(), &'static str> { -+ use bsp::exception::asynchronous::irq_manager; -+ use exception::asynchronous::{interface::IRQManager, IRQDescriptor}; ++ fn register_and_enable_irq_handler( ++ &'static self, ++ irq_number: &Self::IRQNumberType, ++ ) -> Result<(), &'static str> { ++ use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + -+ let descriptor = IRQDescriptor { -+ name: "BCM PL011 UART", -+ handler: self, -+ }; ++ let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + -+ irq_manager().register_handler(self.irq_number, descriptor)?; -+ irq_manager().enable(self.irq_number); ++ irq_manager().register_handler(descriptor)?; ++ irq_manager().enable(irq_number); + + Ok(()) + } } impl console::interface::Write for PL011Uart { -@@ -400,3 +477,24 @@ - self.inner.lock(|inner| inner.chars_read) - } +@@ -405,3 +481,24 @@ } + + impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { @@ -2010,9 +2068,9 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs + } +} -diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs ---- 12_integrated_testing/src/bsp/device_driver/bcm.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs +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. @@ -2026,9 +2084,59 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver/bcm.rs 13_exceptions_part2 +pub use bcm2xxx_interrupt_controller::*; pub use bcm2xxx_pl011_uart::*; -diff -uNr 12_integrated_testing/src/bsp/device_driver.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs ---- 12_integrated_testing/src/bsp/device_driver.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs +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. @@ -2044,48 +2152,114 @@ diff -uNr 12_integrated_testing/src/bsp/device_driver.rs 13_exceptions_part2_per #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; -diff -uNr 12_integrated_testing/src/bsp/raspberrypi/driver.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs ---- 12_integrated_testing/src/bsp/raspberrypi/driver.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs -@@ -12,7 +12,7 @@ +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 @@ - /// Device Driver Manager type. - struct BSPDriverManager { -- device_drivers: [&'static (dyn DeviceDriver + Sync); 2], -+ device_drivers: [&'static (dyn DeviceDriver + Sync); 3], - } + //! 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) }; ++ //-------------------------------------------------------------------------------------------------- -@@ -20,7 +20,11 @@ + // Private Code //-------------------------------------------------------------------------------------------------- +@@ -33,21 +45,43 @@ + Ok(()) + } - static BSP_DRIVER_MANAGER: BSPDriverManager = BSPDriverManager { -- device_drivers: [&super::GPIO, &super::PL011_UART], -+ device_drivers: [ -+ &super::GPIO, -+ &super::PL011_UART, -+ &super::INTERRUPT_CONTROLLER, -+ ], - }; ++/// 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 @@ -diff -uNr 12_integrated_testing/src/bsp/raspberrypi/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs ---- 12_integrated_testing/src/bsp/raspberrypi/exception/asynchronous.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs -@@ -0,0 +1,36 @@ + 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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + -+use crate::{bsp, exception}; ++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}; @@ -2099,34 +2273,23 @@ diff -uNr 12_integrated_testing/src/bsp/raspberrypi/exception/asynchronous.rs 13 + + 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 12_integrated_testing/src/bsp/raspberrypi/exception.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs ---- 12_integrated_testing/src/bsp/raspberrypi/exception.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; -diff -uNr 12_integrated_testing/src/bsp/raspberrypi/memory.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs ---- 12_integrated_testing/src/bsp/raspberrypi/memory.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs -@@ -73,10 +73,12 @@ +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::*; @@ -2134,16 +2297,15 @@ diff -uNr 12_integrated_testing/src/bsp/raspberrypi/memory.rs 13_exceptions_part - 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; ++ 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 +89,8 @@ +@@ -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; @@ -2153,53 +2315,66 @@ diff -uNr 12_integrated_testing/src/bsp/raspberrypi/memory.rs 13_exceptions_part } } -diff -uNr 12_integrated_testing/src/bsp/raspberrypi.rs 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs ---- 12_integrated_testing/src/bsp/raspberrypi.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs -@@ -7,6 +7,7 @@ - pub mod console; +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; //-------------------------------------------------------------------------------------------------- -@@ -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) -+}; + +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}; -diff -uNr 12_integrated_testing/src/cpu/smp.rs 13_exceptions_part2_peripheral_IRQs/src/cpu/smp.rs ---- 12_integrated_testing/src/cpu/smp.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/cpu/smp.rs + /// 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-2022 Andre Richter ++// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + @@ -2212,9 +2387,9 @@ diff -uNr 12_integrated_testing/src/cpu/smp.rs 13_exceptions_part2_peripheral_IR +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; -diff -uNr 12_integrated_testing/src/cpu.rs 13_exceptions_part2_peripheral_IRQs/src/cpu.rs ---- 12_integrated_testing/src/cpu.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/cpu.rs +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; @@ -2225,34 +2400,270 @@ diff -uNr 12_integrated_testing/src/cpu.rs 13_exceptions_part2_peripheral_IRQs/s // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- -diff -uNr 12_integrated_testing/src/driver.rs 13_exceptions_part2_peripheral_IRQs/src/driver.rs ---- 12_integrated_testing/src/driver.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/driver.rs -@@ -23,6 +23,14 @@ +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 handlers, if any. ++ /// 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) -> Result<(), &'static str> { -+ Ok(()) ++ 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 @@ + }) + } - /// Device driver management functions. +- /// 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/src/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs ---- 12_integrated_testing/src/exception/asynchronous.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs -@@ -8,7 +8,145 @@ +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; - -+use core::{fmt, marker::PhantomData}; ++mod null_irq_manager; + ++use crate::{bsp, synchronization}; ++use core::marker::PhantomData; + //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- @@ -2266,14 +2677,23 @@ diff -uNr 12_integrated_testing/src/exception/asynchronous.rs 13_exceptions_part +// Public Definitions +//-------------------------------------------------------------------------------------------------- + ++/// Interrupt number as defined by the BSP. ++pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; ++ +/// Interrupt descriptor. +#[derive(Copy, Clone)] -+pub struct IRQDescriptor { ++pub struct IRQHandlerDescriptor ++where ++ T: Copy, ++{ ++ /// The IRQ number. ++ number: T, ++ + /// Descriptive name. -+ pub name: &'static str, ++ name: &'static str, + + /// Reference to handler trait object. -+ pub handler: &'static (dyn interface::IRQHandler + Sync), ++ handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. @@ -2303,17 +2723,16 @@ diff -uNr 12_integrated_testing/src/exception/asynchronous.rs 13_exceptions_part + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. -+ type IRQNumberType; ++ type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, -+ irq_number: Self::IRQNumberType, -+ descriptor: super::IRQDescriptor, ++ irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. -+ fn enable(&self, irq_number: Self::IRQNumberType); ++ fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// @@ -2329,17 +2748,55 @@ diff -uNr 12_integrated_testing/src/exception/asynchronous.rs 13_exceptions_part + ); + + /// Print list of registered handlers. -+ fn print_handler(&self); ++ fn print_handler(&self) {} + } +} + -+/// A wrapper type for IRQ numbers with integrated range sanity check. -+#[derive(Copy, Clone)] -+pub struct IRQNumber(usize); ++//-------------------------------------------------------------------------------------------------- ++// 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. @@ -2358,55 +2815,37 @@ diff -uNr 12_integrated_testing/src/exception/asynchronous.rs 13_exceptions_part + } +} + -+impl IRQNumber<{ 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 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); -+ } ++ 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/src/lib.rs 13_exceptions_part2_peripheral_IRQs/src/lib.rs ---- 12_integrated_testing/src/lib.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/lib.rs -@@ -108,6 +108,7 @@ - - #![allow(clippy::upper_case_acronyms)] - #![allow(incomplete_features)] -+#![feature(asm_const)] - #![feature(core_intrinsics)] - #![feature(format_args_nl)] - #![feature(linkage)] -@@ -130,6 +131,7 @@ +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; @@ -2415,19 +2854,19 @@ diff -uNr 12_integrated_testing/src/lib.rs 13_exceptions_part2_peripheral_IRQs/s //-------------------------------------------------------------------------------------------------- -diff -uNr 12_integrated_testing/src/main.rs 13_exceptions_part2_peripheral_IRQs/src/main.rs ---- 12_integrated_testing/src/main.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/main.rs -@@ -11,7 +11,7 @@ +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, warn}; ++use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; /// Early init code. /// -@@ -21,7 +21,7 @@ +@@ -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 @@ -2435,84 +2874,79 @@ diff -uNr 12_integrated_testing/src/main.rs 13_exceptions_part2_peripheral_IRQs/ +/// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; -@@ -41,15 +41,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); -+ } -+ } + 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 bsp::console::console; -- use console::interface::All; - use driver::interface::DriverManager; -+ use exception::asynchronous::interface::IRQManager; - +- use console::console; +- info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); -@@ -77,12 +89,9 @@ - info!(" {}. {}", i + 1, driver.compatible()); - } + +@@ -71,12 +74,9 @@ + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); - info!("Echoing input now"); + info!("Registered IRQ handlers:"); -+ bsp::exception::asynchronous::irq_manager().print_handler(); ++ exception::asynchronous::irq_manager().print_handler(); - // Discard any spurious received characters before going into echo mode. - console().clear_rx(); - loop { -- let c = bsp::console::console().read_char(); -- bsp::console::console().write_char(c); +- let c = console().read_char(); +- console().write_char(c); - } + info!("Echoing input now"); + cpu::wait_forever(); } -diff -uNr 12_integrated_testing/src/panic_wait.rs 13_exceptions_part2_peripheral_IRQs/src/panic_wait.rs ---- 12_integrated_testing/src/panic_wait.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/panic_wait.rs +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::{bsp, cpu}; -+use crate::{bsp, cpu, exception}; - use core::{fmt, panic::PanicInfo}; +-use crate::{cpu, println}; ++use crate::{cpu, exception, println}; + use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- -@@ -77,6 +77,8 @@ - fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; +@@ -59,6 +59,8 @@ -+ unsafe { exception::asynchronous::local_irq_mask() }; + #[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/src/state.rs 13_exceptions_part2_peripheral_IRQs/src/state.rs ---- 12_integrated_testing/src/state.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/state.rs +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + @@ -2603,12 +3037,12 @@ diff -uNr 12_integrated_testing/src/state.rs 13_exceptions_part2_peripheral_IRQs + } +} -diff -uNr 12_integrated_testing/src/synchronization.rs 13_exceptions_part2_peripheral_IRQs/src/synchronization.rs ---- 12_integrated_testing/src/synchronization.rs -+++ 13_exceptions_part2_peripheral_IRQs/src/synchronization.rs +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(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } + + /// A reader-writer exclusion type. @@ -2620,10 +3054,10 @@ diff -uNr 12_integrated_testing/src/synchronization.rs 13_exceptions_part2_perip + type Data; + + /// Grants temporary mutable access to the encapsulated data. -+ fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; ++ 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(&self, f: impl FnOnce(&Self::Data) -> R) -> R; ++ fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } } @@ -2685,7 +3119,7 @@ diff -uNr 12_integrated_testing/src/synchronization.rs 13_exceptions_part2_perip +impl interface::Mutex for IRQSafeNullLock { 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 { @@ -72,6 +110,50 @@ // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; @@ -2698,7 +3132,7 @@ diff -uNr 12_integrated_testing/src/synchronization.rs 13_exceptions_part2_perip +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + -+ fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { ++ 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" @@ -2713,7 +3147,7 @@ diff -uNr 12_integrated_testing/src/synchronization.rs 13_exceptions_part2_perip f(data) } + -+ fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { ++ fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) @@ -2738,13 +3172,13 @@ diff -uNr 12_integrated_testing/src/synchronization.rs 13_exceptions_part2_perip + } } -diff -uNr 12_integrated_testing/tests/04_exception_irq_sanity.rs 13_exceptions_part2_peripheral_IRQs/tests/04_exception_irq_sanity.rs ---- 12_integrated_testing/tests/04_exception_irq_sanity.rs -+++ 13_exceptions_part2_peripheral_IRQs/tests/04_exception_irq_sanity.rs +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + @@ -2759,7 +3193,7 @@ diff -uNr 12_integrated_testing/tests/04_exception_irq_sanity.rs 13_exceptions_p + +#[no_mangle] +unsafe fn kernel_init() -> ! { -+ bsp::console::qemu_bring_up_console(); ++ bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); @@ -2775,21 +3209,21 @@ diff -uNr 12_integrated_testing/tests/04_exception_irq_sanity.rs 13_exceptions_p + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + -+ unsafe { exception::asynchronous::local_irq_mask() }; ++ exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. -+ unsafe { exception::asynchronous::local_irq_unmask() }; ++ 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() }; ++ exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + -+ unsafe { exception::asynchronous::local_irq_unmask() }; ++ exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + @@ -2799,13 +3233,13 @@ diff -uNr 12_integrated_testing/tests/04_exception_irq_sanity.rs 13_exceptions_p + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + -+ let first = unsafe { exception::asynchronous::local_irq_mask_save() }; ++ let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + -+ let second = unsafe { exception::asynchronous::local_irq_mask_save() }; ++ let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + -+ unsafe { exception::asynchronous::local_irq_restore(first) }; ++ 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 00000000..3b04b97b --- /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/build.rs b/13_exceptions_part2_peripheral_IRQs/kernel/build.rs similarity index 100% rename from 13_exceptions_part2_peripheral_IRQs/build.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/build.rs diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu.rs similarity index 93% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu.rs index 66da661c..2d010473 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/12_integrated_testing/src/_arch/aarch64/cpu/boot.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.rs similarity index 92% rename from 12_integrated_testing/src/_arch/aarch64/cpu/boot.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.rs index f677c9c4..c80f3ebb 100644 --- a/12_integrated_testing/src/_arch/aarch64/cpu/boot.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,12 +11,16 @@ //! //! crate::cpu::boot::arch_boot +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; -use cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Private Code diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.s b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.s similarity index 85% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.s rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.s index 28b35087..f6df2123 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.s +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.s @@ -18,9 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _EL2, 0x8 -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -32,12 +29,12 @@ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL - cmp x0, _EL2 + 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, _core_id_mask + 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 @@ -60,6 +57,14 @@ _start: 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 diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/smp.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs similarity index 88% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/smp.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs index 351fde62..49192038 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/smp.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural symmetric multiprocessing. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::smp::arch_smp -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs similarity index 88% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs index 495dba34..73019800 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! @@ -11,9 +11,9 @@ //! //! crate::exception::arch_exception -use crate::{bsp, exception}; +use crate::exception; +use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::InMemoryRegister, @@ -46,7 +46,7 @@ struct ExceptionContext { /// Saved program status. spsr_el1: SpsrEL1, - // Exception syndrome register. + /// Exception syndrome register. esr_el1: EsrEL1, } @@ -68,17 +68,17 @@ fn default_exception_handler(exc: &ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } @@ -87,7 +87,7 @@ unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { #[cfg(feature = "test_build")] { const TEST_SVC_ID: u64 = 0x1337; @@ -103,15 +103,13 @@ unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { } #[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); +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] -unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -120,17 +118,17 @@ unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -139,17 +137,17 @@ unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.s b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.s similarity index 97% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.s rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.s index 5aae30b9..91805ee7 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.s +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.s @@ -9,6 +9,7 @@ /// 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 @@ -47,6 +48,9 @@ // 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 diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception/asynchronous.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs similarity index 79% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception/asynchronous.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs index 73b82e65..811ef138 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception/asynchronous.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! @@ -11,8 +11,8 @@ //! //! crate::exception::asynchronous::arch_asynchronous +use aarch64_cpu::registers::*; use core::arch::asm; -use cortex_a::registers::*; use tock_registers::interfaces::{Readable, Writeable}; //-------------------------------------------------------------------------------------------------- @@ -83,42 +83,32 @@ pub fn is_local_irq_masked() -> bool { /// /// "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) - ); +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. -/// -/// # 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) - ); +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). -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. #[inline(always)] -pub unsafe fn local_irq_mask_save() -> u64 { +pub fn local_irq_mask_save() -> u64 { let saved = DAIF.get(); local_irq_mask(); @@ -127,12 +117,11 @@ pub unsafe fn local_irq_mask_save() -> u64 { /// Restore the interrupt mask bits (DAIF) using the callee's argument. /// -/// # Safety +/// # Invariant /// -/// - Changes the HW state of the executing core. /// - No sanity checks on the input. #[inline(always)] -pub unsafe fn local_irq_restore(saved: u64) { +pub fn local_irq_restore(saved: u64) { DAIF.set(saved); } diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs similarity index 98% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs index 15a7faeb..99ecaa2b 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! @@ -17,8 +17,8 @@ use crate::{ bsp, memory, memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, }; +use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- diff --git a/12_integrated_testing/src/_arch/aarch64/memory/mmu/translation_table.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs similarity index 99% rename from 12_integrated_testing/src/_arch/aarch64/memory/mmu/translation_table.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs index 78776126..5e45a5fd 100644 --- a/12_integrated_testing/src/_arch/aarch64/memory/mmu/translation_table.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! 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 00000000..ee1c3ef7 --- /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/15_virtual_mem_part3_precomputed_tables/src/bsp.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp.rs similarity index 81% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp.rs index 824787f6..246973bc 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs similarity index 82% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs index eafaf775..2dfaec8d 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs similarity index 64% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs index e83e24c9..8d1cbfbd 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs similarity index 88% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs index 09a0cdf4..d8744fec 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICv2 Driver - ARM Generic Interrupt Controller v2. //! @@ -79,20 +79,25 @@ mod gicc; mod gicd; -use crate::{bsp, cpu, driver, exception, synchronization, synchronization::InitStateLock}; +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, synchronization, + synchronization::InitStateLock, +}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- -type HandlerTable = [Option; GICv2::NUM_IRQS]; +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; /// Representation of the GIC. pub struct GICv2 { @@ -112,7 +117,8 @@ pub struct GICv2 { 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; + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; /// Create an instance. /// @@ -123,7 +129,7 @@ impl GICv2 { 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]), + handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), } } } @@ -134,8 +140,10 @@ impl GICv2 { use synchronization::interface::ReadWriteEx; impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "GICv2 (ARM Generic Interrupt Controller v2)" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { @@ -155,23 +163,22 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { - let irq_number = irq_number.get(); + let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } - table[irq_number] = Some(descriptor); + table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } - fn enable(&self, irq_number: Self::IRQNumberType) { + fn enable(&self, irq_number: &Self::IRQNumberType) { self.gicd.enable(irq_number); } @@ -194,7 +201,7 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { 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"); + descriptor.handler().handle().expect("Error handling IRQ"); } } }); @@ -211,7 +218,7 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { 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); + info!(" {: >3}. {}", i + 32, handler.name()); } } }); diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs similarity index 98% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs index 2d2eebc6..ce8ffa72 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICC Driver - GIC CPU interface. diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs similarity index 97% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs index bc7f7f23..1d528ca5 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICD Driver - GIC Distributor. //! @@ -50,9 +50,9 @@ register_structs! { (0x004 => TYPER: ReadOnly), (0x008 => _reserved1), (0x104 => ISENABLER: [ReadWrite; 31]), - (0x108 => _reserved2), + (0x180 => _reserved2), (0x820 => ITARGETSR: [ReadWrite; 248]), - (0x824 => @END), + (0xC00 => @END), } } @@ -63,7 +63,7 @@ register_structs! { (0x100 => ISENABLER: ReadWrite), (0x104 => _reserved2), (0x800 => ITARGETSR: [ReadOnly; 8]), - (0x804 => @END), + (0x820 => @END), } } @@ -170,7 +170,7 @@ impl GICD { } /// Enable an interrupt. - pub fn enable(&self, irq_num: super::IRQNumber) { + 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 diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs similarity index 83% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs index 5a7cc23b..7b7c288b 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs similarity index 90% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs index c0dc838a..353bcc8c 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::IRQSafeNullLock, + bsp::device_driver::common::MMIODerefWrapper, driver, exception::asynchronous::IRQNumber, + synchronization, synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -143,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. @@ -189,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -213,7 +216,9 @@ impl GPIO { use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "BCM GPIO" + Self::COMPATIBLE } } diff --git a/13_exceptions_part2_peripheral_IRQs/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 similarity index 64% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs index 577470d4..dfcbbaa7 100644 --- a/13_exceptions_part2_peripheral_IRQs/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 @@ -1,12 +1,17 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Interrupt Controller Driver. mod peripheral_ic; -use crate::{driver, exception}; +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, +}; +use core::fmt; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -21,13 +26,12 @@ struct PendingIRQs { // Public Definitions //-------------------------------------------------------------------------------------------------- -pub type LocalIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -pub type PeripheralIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; +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), @@ -52,16 +56,13 @@ impl Iterator for PendingIRQs { type Item = usize; fn next(&mut self) -> Option { - use core::intrinsics::cttz; - - let next = cttz(self.bitmask); - if next == 64 { + if self.bitmask == 0 { return None; } - self.bitmask &= !(1 << next); - - Some(next as usize) + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) } } @@ -69,17 +70,28 @@ impl Iterator for PendingIRQs { // 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 { - const MAX_LOCAL_IRQ_NUMBER: usize = 11; + // 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; - const NUM_PERIPHERAL_IRQS: usize = Self::MAX_PERIPHERAL_IRQ_NUMBER + 1; + + 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: usize, periph_mmio_start_addr: usize) -> Self { + pub const unsafe fn new(periph_mmio_start_addr: usize) -> Self { Self { periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), } @@ -91,8 +103,10 @@ impl InterruptController { //------------------------------------------------------------------------------ impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "BCM Interrupt Controller" + Self::COMPATIBLE } } @@ -101,16 +115,23 @@ impl exception::asynchronous::interface::IRQManager for InterruptController { fn register_handler( &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { - match irq { + match irq_handler_descriptor.number() { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), - IRQNumber::Peripheral(pirq) => self.periph.register_handler(pirq, 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) { + fn enable(&self, irq: &Self::IRQNumberType) { match irq { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), diff --git a/13_exceptions_part2_peripheral_IRQs/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 similarity index 85% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs index 3107d296..b4c56f44 100644 --- a/13_exceptions_part2_peripheral_IRQs/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 @@ -1,10 +1,14 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - -use super::{InterruptController, PendingIRQs, PeripheralIRQ}; +use super::{PendingIRQs, PeripheralIRQ}; use crate::{ bsp::device_driver::common::MMIODerefWrapper, exception, synchronization, @@ -26,7 +30,7 @@ register_structs! { (0x00 => _reserved1), (0x10 => ENABLE_1: WriteOnly), (0x14 => ENABLE_2: WriteOnly), - (0x24 => @END), + (0x18 => @END), } } @@ -46,8 +50,8 @@ type WriteOnlyRegisters = MMIODerefWrapper; /// Abstraction for the ReadOnly parts of the associated MMIO registers. type ReadOnlyRegisters = MMIODerefWrapper; -type HandlerTable = - [Option; InterruptController::NUM_PERIPHERAL_IRQS]; +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -79,7 +83,7 @@ impl PeripheralIC { 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]), + handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), } } @@ -102,23 +106,22 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { fn register_handler( &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { - let irq_number = irq.get(); + let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } - table[irq_number] = Some(descriptor); + table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } - fn enable(&self, irq: Self::IRQNumberType) { + fn enable(&self, irq: &Self::IRQNumberType) { self.wo_registers.lock(|regs| { let enable_reg = if irq.get() <= 31 { ®s.ENABLE_1 @@ -144,7 +147,7 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { 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"); + descriptor.handler().handle().expect("Error handling IRQ"); } } } @@ -159,7 +162,7 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { self.handler_table.read(|table| { for (i, opt) in table.iter().enumerate() { if let Some(handler) = opt { - info!(" {: >3}. {}", i, handler.name); + info!(" {: >3}. {}", i, handler.name()); } } }); diff --git a/13_exceptions_part2_peripheral_IRQs/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 similarity index 93% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs index af573fd0..fbbbee56 100644 --- a/13_exceptions_part2_peripheral_IRQs/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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -10,8 +10,11 @@ //! - use crate::{ - bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, - synchronization, synchronization::IRQSafeNullLock, + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + synchronization, + synchronization::IRQSafeNullLock, }; use core::fmt; use tock_registers::{ @@ -216,27 +219,23 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { inner: IRQSafeNullLock, - irq_number: bsp::device_driver::IRQNumber, } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -384,19 +383,21 @@ 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. - pub const unsafe fn new( - mmio_start_addr: usize, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { + pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), - irq_number, } } } @@ -407,8 +408,10 @@ impl PL011Uart { use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "BCM PL011 UART" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { @@ -417,17 +420,16 @@ impl driver::interface::DeviceDriver for PL011Uart { Ok(()) } - fn register_and_enable_irq_handler(&'static self) -> Result<(), &'static str> { - use bsp::exception::asynchronous::irq_manager; - use exception::asynchronous::{interface::IRQManager, IRQDescriptor}; + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; - let descriptor = IRQDescriptor { - name: "BCM PL011 UART", - handler: self, - }; + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); - irq_manager().register_handler(self.irq_number, descriptor)?; - irq_manager().enable(self.irq_number); + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); Ok(()) } @@ -441,7 +443,7 @@ 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)) } @@ -478,6 +480,8 @@ impl console::interface::Statistics for PL011Uart { } } +impl console::interface::All for PL011Uart {} + impl exception::asynchronous::interface::IRQHandler for PL011Uart { fn handle(&self) -> Result<(), &'static str> { self.inner.lock(|inner| { diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/common.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs similarity index 54% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/common.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs index fd9e988e..90027e47 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/common.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Common device driver code. -use core::{marker::PhantomData, ops}; +use core::{fmt, marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -15,6 +15,10 @@ pub struct MMIODerefWrapper { 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 @@ impl ops::Deref for MMIODerefWrapper { 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 00000000..30421dfa --- /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/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/cpu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/cpu.rs similarity index 87% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/cpu.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/cpu.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. 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 00000000..d17272dd --- /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/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs similarity index 67% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs index aa6c5a63..a9eaa6ac 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs similarity index 56% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs index dc5ab421..776182fd 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception/asynchronous.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -1,15 +1,18 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! BSP asynchronous exception handling. -use crate::{bsp, exception}; +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}; @@ -23,14 +26,3 @@ pub(in crate::bsp) mod irq_map { 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/12_integrated_testing/src/bsp/raspberrypi/link.ld b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld similarity index 88% rename from 12_integrated_testing/src/bsp/raspberrypi/link.ld rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld index 2ce4b44b..6d939889 100644 --- a/12_integrated_testing/src/bsp/raspberrypi/link.ld +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld @@ -60,7 +60,6 @@ SECTIONS } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; @@ -78,4 +77,12 @@ SECTIONS . = 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/src/bsp/raspberrypi/memory.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs similarity index 88% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs index 51b334c0..44cefe33 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! @@ -73,12 +73,11 @@ pub(super) mod map { 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 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. diff --git a/12_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs similarity index 98% rename from 12_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs index f8cdc82f..563c8ba9 100644 --- a/12_integrated_testing/src/bsp/raspberrypi/memory/mmu.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. 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 00000000..782a5da1 --- /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/15_virtual_mem_part3_precomputed_tables/src/console.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs similarity index 52% rename from 15_virtual_mem_part3_precomputed_tables/src/console.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs index e49e241f..f0363464 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/console.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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: 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 00000000..e92a022b --- /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/src/cpu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs similarity index 89% rename from 13_exceptions_part2_peripheral_IRQs/src/cpu.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs index e1493d1d..8716a918 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/cpu.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/13_exceptions_part2_peripheral_IRQs/src/cpu/boot.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/boot.rs similarity index 71% rename from 13_exceptions_part2_peripheral_IRQs/src/cpu/boot.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/cpu/boot.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/16_virtual_mem_part4_higher_half_kernel/src/cpu/smp.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs similarity index 87% rename from 16_virtual_mem_part4_higher_half_kernel/src/cpu/smp.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs index 57386f79..de612d58 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/cpu/smp.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Symmetric multiprocessing. 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 00000000..2edf8b85 --- /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/12_integrated_testing/src/exception.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception.rs similarity index 94% rename from 12_integrated_testing/src/exception.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/exception.rs index f4af8144..3d5f219f 100644 --- a/12_integrated_testing/src/exception.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. @@ -21,7 +21,7 @@ pub use arch_exception::{current_privilege_level, handling_init}; /// Kernel privilege levels. #[allow(missing_docs)] -#[derive(PartialEq)] +#[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, diff --git a/14_virtual_mem_part2_mmio_remap/src/exception/asynchronous.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs similarity index 63% rename from 14_virtual_mem_part2_mmio_remap/src/exception/asynchronous.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs index fb1785c2..2c874dd6 100644 --- a/14_virtual_mem_part2_mmio_remap/src/exception/asynchronous.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs @@ -1,14 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// 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 core::{fmt, marker::PhantomData}; +use crate::{bsp, synchronization}; +use core::marker::PhantomData; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports @@ -22,14 +24,23 @@ pub use arch_asynchronous::{ // Public Definitions //-------------------------------------------------------------------------------------------------- +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + /// Interrupt descriptor. #[derive(Copy, Clone)] -pub struct IRQDescriptor { +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + /// Descriptive name. - pub name: &'static str, + name: &'static str, /// Reference to handler trait object. - pub handler: &'static (dyn interface::IRQHandler + Sync), + handler: &'static (dyn interface::IRQHandler + Sync), } /// IRQContext token. @@ -59,17 +70,16 @@ pub mod interface { /// platform's interrupt controller. pub trait IRQManager { /// The IRQ number type depends on the implementation. - type IRQNumberType; + type IRQNumberType: Copy; /// Register a handler. fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: super::IRQDescriptor, + irq_handler_descriptor: super::IRQHandlerDescriptor, ) -> Result<(), &'static str>; /// Enable an interrupt in the controller. - fn enable(&self, irq_number: Self::IRQNumberType); + fn enable(&self, irq_number: &Self::IRQNumberType); /// Handle pending interrupts. /// @@ -85,17 +95,55 @@ pub mod interface { ); /// Print list of registered handlers. - fn print_handler(&self); + fn print_handler(&self) {} } } -/// A wrapper type for IRQ numbers with integrated range sanity check. -#[derive(Copy, Clone)] -pub struct IRQNumber(usize); +//-------------------------------------------------------------------------------------------------- +// 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. @@ -114,39 +162,29 @@ impl<'irq_context> IRQContext<'irq_context> { } } -impl IRQNumber<{ 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 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); - } + 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 00000000..38919ffe --- /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/15_virtual_mem_part3_precomputed_tables/src/lib.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs similarity index 95% rename from 15_virtual_mem_part3_precomputed_tables/src/lib.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs index 9ed0941c..a8783f6c 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/lib.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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` library. //! @@ -109,13 +111,15 @@ #![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(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)] @@ -180,8 +184,7 @@ pub fn test_runner(tests: &[&test_types::UnitTest]) { #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); test_main(); diff --git a/13_exceptions_part2_peripheral_IRQs/src/main.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs similarity index 63% rename from 13_exceptions_part2_peripheral_IRQs/src/main.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs index 6729d45c..e524322d 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/main.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. @@ -11,7 +13,7 @@ #![no_main] #![no_std] -use libkernel::{bsp, cpu, driver, exception, info, memory, state, time, warn}; +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; /// Early init code. /// @@ -24,7 +26,6 @@ use libkernel::{bsp, cpu, driver, exception, info, memory, state, time, warn}; /// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; use memory::mmu::interface::MMU; exception::handling_init(); @@ -33,21 +34,14 @@ unsafe fn kernel_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); - } + // 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(); @@ -60,9 +54,6 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { - use driver::interface::DriverManager; - use exception::asynchronous::interface::IRQManager; - info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); @@ -81,16 +72,10 @@ fn kernel_main() -> ! { ); info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); info!("Registered IRQ handlers:"); - bsp::exception::asynchronous::irq_manager().print_handler(); + exception::asynchronous::irq_manager().print_handler(); info!("Echoing input now"); cpu::wait_forever(); diff --git a/13_exceptions_part2_peripheral_IRQs/src/memory.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs similarity index 58% rename from 13_exceptions_part2_peripheral_IRQs/src/memory.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs index ac6663b3..6dd8f186 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/memory.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management. diff --git a/12_integrated_testing/src/memory/mmu.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs similarity index 94% rename from 12_integrated_testing/src/memory/mmu.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs index a68973e7..7c7fc397 100644 --- a/12_integrated_testing/src/memory/mmu.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. //! @@ -20,6 +20,7 @@ mod arch_mmu; mod translation_table; +use crate::common; use core::{fmt, ops::RangeInclusive}; //-------------------------------------------------------------------------------------------------- @@ -178,19 +179,7 @@ impl fmt::Display for TranslationDescriptor { 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 (size, unit) = common::size_human_readable_ceil(size); let attr = match self.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", diff --git a/12_integrated_testing/src/memory/mmu/translation_table.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs similarity index 88% rename from 12_integrated_testing/src/memory/mmu/translation_table.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs index 88e3fe48..1a2581aa 100644 --- a/12_integrated_testing/src/memory/mmu/translation_table.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Translation table. diff --git a/12_integrated_testing/src/panic_wait.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs similarity index 80% rename from 12_integrated_testing/src/panic_wait.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs index 6f09f11c..c6f3a9c7 100644 --- a/12_integrated_testing/src/panic_wait.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs @@ -1,22 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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, exception, println}; +use core::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 `libkernel`. /// /// It is linked weakly, so that the integration tests can overload its standard behavior. @@ -34,16 +28,6 @@ fn _panic_exit() -> ! { } } -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -75,7 +59,7 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; + exception::asynchronous::local_irq_mask(); // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -86,7 +70,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/13_exceptions_part2_peripheral_IRQs/src/print.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/print.rs similarity index 85% rename from 13_exceptions_part2_peripheral_IRQs/src/print.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/print.rs index 9ec13a28..8e303046 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/print.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/14_virtual_mem_part2_mmio_remap/src/state.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs similarity index 97% rename from 14_virtual_mem_part2_mmio_remap/src/state.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs index 0af3688c..6d99beed 100644 --- a/14_virtual_mem_part2_mmio_remap/src/state.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! State information about the kernel itself. diff --git a/14_virtual_mem_part2_mmio_remap/src/synchronization.rs b/13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs similarity index 89% rename from 14_virtual_mem_part2_mmio_remap/src/synchronization.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs index 4b4c4c3f..5740b63e 100644 --- a/14_virtual_mem_part2_mmio_remap/src/synchronization.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } /// A reader-writer exclusion type. @@ -38,10 +38,10 @@ pub mod interface { type Data; /// Grants temporary mutable access to the encapsulated data. - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; + 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(&self, f: impl FnOnce(&Self::Data) -> R) -> R; + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; } } @@ -105,7 +105,7 @@ use crate::{exception, state}; impl interface::Mutex for IRQSafeNullLock { 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() }; @@ -118,7 +118,7 @@ impl interface::Mutex for IRQSafeNullLock { impl interface::ReadWriteEx for InitStateLock { type Data = T; - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { + 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" @@ -133,7 +133,7 @@ impl interface::ReadWriteEx for InitStateLock { f(data) } - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { let data = unsafe { &*self.data.get() }; f(data) 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 00000000..a9d50120 --- /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/14_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rb b/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rb similarity index 81% rename from 14_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rb rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rb index 48c9703d..8be7a2f1 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rb +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2019-2022 Andre Richter +# Copyright (c) 2019-2023 Andre Richter -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify sending and receiving works as expected. class TxRxHandshakeTest < SubtestBase @@ -40,9 +40,9 @@ class RxStatisticsTest < SubtestBase end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Test registration -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- def subtest_collection [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] end diff --git a/14_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs similarity index 82% rename from 14_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs index dccb6cc2..982c6170 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Console sanity tests - RX, TX and statistics. @@ -15,11 +15,10 @@ use libkernel::{bsp, console, cpu, exception, print}; #[no_mangle] unsafe fn kernel_init() -> ! { - use bsp::console::console; - use console::interface::*; + use console::console; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); diff --git a/14_virtual_mem_part2_mmio_remap/tests/01_timer_sanity.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs similarity index 83% rename from 14_virtual_mem_part2_mmio_remap/tests/01_timer_sanity.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs index 59ef4a7f..3b065f13 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/01_timer_sanity.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Timer sanity tests. @@ -11,13 +11,13 @@ #![test_runner(libkernel::test_runner)] use core::time::Duration; -use libkernel::{bsp, cpu, exception, time, time::interface::TimeManager}; +use libkernel::{bsp, cpu, exception, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. @@ -35,6 +35,7 @@ fn timer_is_counting() { /// 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) } diff --git a/13_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs similarity index 92% rename from 13_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs index 9be94acd..bf5b7d71 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. @@ -24,7 +24,7 @@ unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + 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"); diff --git a/12_integrated_testing/tests/03_exception_restore_sanity.rb b/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rb similarity index 65% rename from 12_integrated_testing/tests/03_exception_restore_sanity.rb rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rb index c3c725ed..02f51f74 100644 --- a/12_integrated_testing/tests/03_exception_restore_sanity.rb +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2022 Andre Richter +# Copyright (c) 2022-2023 Andre Richter -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify that exception restore works. class ExceptionRestoreTest < SubtestBase @@ -17,9 +17,9 @@ class ExceptionRestoreTest < SubtestBase end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Test registration -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- def subtest_collection [ExceptionRestoreTest.new] end diff --git a/12_integrated_testing/tests/03_exception_restore_sanity.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs similarity index 92% rename from 12_integrated_testing/tests/03_exception_restore_sanity.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs index f25ed645..e22f4977 100644 --- a/12_integrated_testing/tests/03_exception_restore_sanity.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter //! A simple sanity test to see if exception restore code works. @@ -33,7 +33,7 @@ unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); diff --git a/14_virtual_mem_part2_mmio_remap/tests/04_exception_irq_sanity.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs similarity index 70% rename from 14_virtual_mem_part2_mmio_remap/tests/04_exception_irq_sanity.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs index e1e02554..e37896b8 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/04_exception_irq_sanity.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! IRQ handling sanity tests. @@ -15,7 +15,7 @@ use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { - bsp::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); exception::handling_init(); exception::asynchronous::local_irq_unmask(); @@ -31,21 +31,21 @@ fn local_irq_mask_works() { // Precondition: IRQs are unmasked. assert!(exception::asynchronous::is_local_irq_masked()); - unsafe { exception::asynchronous::local_irq_mask() }; + exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); // Restore earlier state. - unsafe { exception::asynchronous::local_irq_unmask() }; + 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() }; + exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); - unsafe { exception::asynchronous::local_irq_unmask() }; + exception::asynchronous::local_irq_unmask(); assert!(exception::asynchronous::is_local_irq_masked()); } @@ -55,12 +55,12 @@ 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() }; + let first = exception::asynchronous::local_irq_mask_save(); assert!(!exception::asynchronous::is_local_irq_masked()); - let second = unsafe { exception::asynchronous::local_irq_mask_save() }; + let second = exception::asynchronous::local_irq_mask_save(); assert_ne!(first, second); - unsafe { exception::asynchronous::local_irq_restore(first) }; + exception::asynchronous::local_irq_restore(first); assert!(exception::asynchronous::is_local_irq_masked()); } diff --git a/13_exceptions_part2_peripheral_IRQs/tests/boot_test_string.rb b/13_exceptions_part2_peripheral_IRQs/kernel/tests/boot_test_string.rb similarity index 100% rename from 13_exceptions_part2_peripheral_IRQs/tests/boot_test_string.rb rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/boot_test_string.rb diff --git a/12_integrated_testing/tests/panic_exit_success/mod.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_exit_success/mod.rs similarity index 77% rename from 12_integrated_testing/tests/panic_exit_success/mod.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_exit_success/mod.rs index 908fac51..449ad6f9 100644 --- a/12_integrated_testing/tests/panic_exit_success/mod.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_exit_success/mod.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter /// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. #[no_mangle] diff --git a/14_virtual_mem_part2_mmio_remap/tests/panic_wait_forever/mod.rs b/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_wait_forever/mod.rs similarity index 74% rename from 14_virtual_mem_part2_mmio_remap/tests/panic_wait_forever/mod.rs rename to 13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_wait_forever/mod.rs index 7a4effa5..9ac19144 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/panic_wait_forever/mod.rs +++ b/13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_wait_forever/mod.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter /// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. #[no_mangle] diff --git a/13_exceptions_part2_peripheral_IRQs/test-macros/Cargo.toml b/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/Cargo.toml similarity index 100% rename from 13_exceptions_part2_peripheral_IRQs/test-macros/Cargo.toml rename to 13_exceptions_part2_peripheral_IRQs/libraries/test-macros/Cargo.toml diff --git a/14_virtual_mem_part2_mmio_remap/test-macros/src/lib.rs b/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/src/lib.rs similarity index 85% rename from 14_virtual_mem_part2_mmio_remap/test-macros/src/lib.rs rename to 13_exceptions_part2_peripheral_IRQs/libraries/test-macros/src/lib.rs index 83025a09..52cf893d 100644 --- a/14_virtual_mem_part2_mmio_remap/test-macros/src/lib.rs +++ b/13_exceptions_part2_peripheral_IRQs/libraries/test-macros/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter use proc_macro::TokenStream; use proc_macro2::Span; @@ -11,7 +11,7 @@ use syn::{parse_macro_input, Ident, ItemFn}; 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_name = &format!("{}", f.sig.ident); let test_ident = Ident::new( &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), Span::call_site(), diff --git a/13_exceptions_part2_peripheral_IRQs/test-types/Cargo.toml b/13_exceptions_part2_peripheral_IRQs/libraries/test-types/Cargo.toml similarity index 100% rename from 13_exceptions_part2_peripheral_IRQs/test-types/Cargo.toml rename to 13_exceptions_part2_peripheral_IRQs/libraries/test-types/Cargo.toml diff --git a/15_virtual_mem_part3_precomputed_tables/test-types/src/lib.rs b/13_exceptions_part2_peripheral_IRQs/libraries/test-types/src/lib.rs similarity index 82% rename from 15_virtual_mem_part3_precomputed_tables/test-types/src/lib.rs rename to 13_exceptions_part2_peripheral_IRQs/libraries/test-types/src/lib.rs index 922c2a1c..38961a9c 100644 --- a/15_virtual_mem_part3_precomputed_tables/test-types/src/lib.rs +++ b/13_exceptions_part2_peripheral_IRQs/libraries/test-types/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Types for the `custom_test_frameworks` implementation. diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/time.rs b/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/time.rs deleted file mode 100644 index c814219c..00000000 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } -} - -//-------------------------------------------------------------------------------------------------- -// 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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; - - 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) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs b/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs deleted file mode 100644 index 97656a27..00000000 --- a/13_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-2022 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/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs b/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs deleted file mode 100644 index eaef0b1f..00000000 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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. -#[cfg(feature = "test_build")] -pub fn qemu_bring_up_console() {} diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs b/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index 1cf6d23c..00000000 --- a/13_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-2022 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/13_exceptions_part2_peripheral_IRQs/src/driver.rs b/13_exceptions_part2_peripheral_IRQs/src/driver.rs deleted file mode 100644 index 8c5c5e16..00000000 --- a/13_exceptions_part2_peripheral_IRQs/src/driver.rs +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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/13_exceptions_part2_peripheral_IRQs/src/time.rs b/13_exceptions_part2_peripheral_IRQs/src/time.rs deleted file mode 100644 index 6d92b196..00000000 --- a/13_exceptions_part2_peripheral_IRQs/src/time.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020-2022 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; - -//-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports -//-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - 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_virtual_mem_part2_mmio_remap/.vscode/settings.json b/14_virtual_mem_part2_mmio_remap/.vscode/settings.json index 0a8d7c09..9ef30cd0 100644 --- a/14_virtual_mem_part2_mmio_remap/.vscode/settings.json +++ b/14_virtual_mem_part2_mmio_remap/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index ab4eda71..eea03734 100644 --- a/14_virtual_mem_part2_mmio_remap/Cargo.lock +++ b/14_virtual_mem_part2_mmio_remap/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,8 +15,7 @@ dependencies = [ name = "mingo" version = "0.14.0" dependencies = [ - "cortex-a", - "mingo", + "aarch64-cpu", "qemu-exit", "test-macros", "test-types", @@ -25,11 +24,11 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.37" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" dependencies = [ - "unicode-xid", + "unicode-ident", ] [[package]] @@ -40,22 +39,22 @@ checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" [[package]] name = "quote" -version = "1.0.17" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "syn" -version = "1.0.91" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" dependencies = [ "proc-macro2", "quote", - "unicode-xid", + "unicode-ident", ] [[package]] @@ -74,12 +73,12 @@ version = "0.1.0" [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" [[package]] -name = "unicode-xid" -version = "0.2.2" +name = "unicode-ident" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/14_virtual_mem_part2_mmio_remap/Cargo.toml b/14_virtual_mem_part2_mmio_remap/Cargo.toml index 130d80f7..6480a727 100644 --- a/14_virtual_mem_part2_mmio_remap/Cargo.toml +++ b/14_virtual_mem_part2_mmio_remap/Cargo.toml @@ -1,67 +1,9 @@ -[package] -name = "mingo" -version = "0.14.0" -authors = ["Andre Richter "] -edition = "2021" +[workspace] + +members = [ + "libraries/*", + "kernel" +] [profile.release] lto = true - -[features] -default = [] -bsp_rpi3 = ["tock-registers"] -bsp_rpi4 = ["tock-registers"] -test_build = ["qemu-exit"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] -test-types = { path = "test-types" } - -# Optional dependencies -tock-registers = { version = "0.7.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] -cortex-a = { version = "7.x.x" } - -##-------------------------------------------------------------------------------------------------- -## Testing -##-------------------------------------------------------------------------------------------------- - -[dev-dependencies] -test-macros = { path = "test-macros" } - -# The following line is a workaround, as suggested in [1], to enable a feature in test-builds only. -# This allows building the library part of the kernel with specialized code for testing. -# -# -# [1] https://github.com/rust-lang/cargo/issues/2911#issuecomment-749580481 -mingo = { path = ".", features = ["test_build"] } - -# 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/Makefile b/14_virtual_mem_part2_mmio_remap/Makefile index afa22480..4e2efeff 100644 --- a/14_virtual_mem_part2_mmio_remap/Makefile +++ b/14_virtual_mem_part2_mmio_remap/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -41,7 +42,7 @@ ifeq ($(BSP),rpi3) 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 + 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 @@ -55,7 +56,7 @@ else ifeq ($(BSP),rpi4) 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 + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif @@ -67,14 +68,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -94,11 +95,10 @@ COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -TEST_CMD = cargo test $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary @@ -167,7 +167,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -203,6 +203,8 @@ chainboot: $(KERNEL_BIN) ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean @@ -225,7 +227,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -235,12 +236,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- @@ -277,6 +272,8 @@ gdb gdb-opt0: $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- .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: @@ -295,7 +292,11 @@ test_boot: $(KERNEL_BIN) ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER - #!/usr/bin/env bash +#!/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') diff --git a/14_virtual_mem_part2_mmio_remap/README.md b/14_virtual_mem_part2_mmio_remap/README.md index 07a82cda..e21ad501 100644 --- a/14_virtual_mem_part2_mmio_remap/README.md +++ b/14_virtual_mem_part2_mmio_remap/README.md @@ -8,8 +8,7 @@ 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) - during the device driver's `init()`. + - Device `MMIO regions` are remapped lazily (to a special reserved virtual address region). ## Table of Contents @@ -59,7 +58,8 @@ separation, this tutorial makes a start by changing the following things: 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 a device driver's `init()`. +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 @@ -232,43 +232,78 @@ pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { } ``` -Another user of the new APIs are device drivers, which now expect an `MMIODescriptor` type instead -of a raw address. The following is an example for the `UART`: +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 -impl PL011Uart { - /// Create an instance. - pub const unsafe fn new( - mmio_descriptor: memory::mmu::MMIODescriptor, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { - Self { - // omitted for brevity. - } - } -} +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(); ``` -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: +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 -unsafe fn init(&self) -> Result<(), &'static str> { - let virt_addr = memory::mmu::kernel_map_mmio(self.compatible(), &self.mmio_descriptor)?; +/// 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(()) +} +``` - self.inner - .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; +```rust +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; - // omitted for brevity. + 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 -Peeking inside `memory::mmu::kernel_map_mmio()`, we can see that a `virtual address region` is -obtained from an `allocator` before remapping: +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( @@ -279,7 +314,7 @@ pub unsafe fn kernel_map_mmio( // omitted let virt_region = - alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; kernel_map_at_unchecked( name, @@ -296,10 +331,11 @@ pub unsafe fn kernel_map_mmio( } ``` -This allocator is defined and implemented in the added file `src/memory/mmu/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`](src/memory/mmu/types.rs)), but apart -from that is rather straight forward. Therefore, it won't be covered in details here. +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? @@ -313,7 +349,7 @@ been turned on. fn kernel_init_mmio_va_allocator() { let region = bsp::memory::mmu::virt_mmio_remap_region(); - alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.initialize(region)); + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); } ``` @@ -338,16 +374,17 @@ the VA range. ### Supporting Changes -There's a couple of changes not covered in this tutorial text, but the reader should ideally skim -through them: +There's a couple of changes more not covered in this tutorial text, but the reader should ideally +skim through them: -- [`src/memory.rs`](src/memory.rs) and [`src/memory/mmu/types.rs`](src/memory/mmu/types.rs) - introduce a couple of supporting types, like`Address`, `PageAddress` and - `MemoryRegion`. It is worth reading their implementations. -- [`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. +- [`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 @@ -373,22 +410,22 @@ Minipush 1.0 Raspberry Pi 3 [ML] Requesting binary -[MP] ⏩ Pushing 67 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[MP] ⏩ Pushing 65 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now -[ 0.758253] mingo version 0.14.0 -[ 0.758460] Booting on: Raspberry Pi 3 -[ 0.758915] MMU online: -[ 0.759208] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 0.760952] Virtual Physical Size Attr Entity -[ 0.762696] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 0.764441] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack -[ 0.766044] 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.767658] 0x0000_0000_0009_0000..0x0000_0000_000d_ffff --> 0x00_0009_0000..0x00_000d_ffff | 320 KiB | C RW XN | Kernel data and bss -[ 0.769229] 0x0000_0000_000e_0000..0x0000_0000_000e_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM GPIO -[ 0.770680] | BCM PL011 UART -[ 0.772197] 0x0000_0000_000f_0000..0x0000_0000_000f_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Peripheral Interrupt Controller -[ 0.773941] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 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: @@ -410,32 +447,31 @@ Minipush 1.0 Raspberry Pi 4 [ML] Requesting binary -[MP] ⏩ Pushing 74 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 +[MP] ⏩ Pushing 65 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now -[ 0.842275] mingo version 0.14.0 -[ 0.842308] Booting on: Raspberry Pi 4 -[ 0.842763] MMU online: -[ 0.843055] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 0.844800] Virtual Physical Size Attr Entity -[ 0.846544] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 0.848288] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack -[ 0.849892] 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.851505] 0x0000_0000_0009_0000..0x0000_0000_000d_ffff --> 0x00_0009_0000..0x00_000d_ffff | 320 KiB | C RW XN | Kernel data and bss -[ 0.853076] 0x0000_0000_000e_0000..0x0000_0000_000e_ffff --> 0x00_fe20_0000..0x00_fe20_ffff | 64 KiB | Dev RW XN | BCM GPIO -[ 0.854528] | BCM PL011 UART -[ 0.856045] 0x0000_0000_000f_0000..0x0000_0000_000f_ffff --> 0x00_ff84_0000..0x00_ff84_ffff | 64 KiB | Dev RW XN | GICD -[ 0.857453] | GICC -[ 0.858862] ------------------------------------------------------------------------------------------------------------------------------------------- - +[ 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/Cargo.toml 14_virtual_mem_part2_mmio_remap/Cargo.toml ---- 13_exceptions_part2_peripheral_IRQs/Cargo.toml -+++ 14_virtual_mem_part2_mmio_remap/Cargo.toml +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" @@ -445,9 +481,9 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/Cargo.toml 14_virtual_mem_part2_mm edition = "2021" -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu/translation_table.rs 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu/translation_table.rs ---- 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu/translation_table.rs -+++ 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu/translation_table.rs +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 @@ -705,9 +741,9 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu/trans use super::*; use test_macros::kernel_test; -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs ---- 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs -+++ 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs +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::{ @@ -715,8 +751,8 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs 14 - memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, + memory::{mmu::TranslationGranule, Address, Physical}, }; + use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; - use cortex_a::{asm::barrier, registers::*}; @@ -46,13 +46,6 @@ // Global instances //-------------------------------------------------------------------------------------------------- @@ -802,638 +838,411 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/memory/mmu.rs 14 - } -} -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicc.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs -@@ -4,7 +4,9 @@ +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, synchronization::InitStateLock, ++ bsp::device_driver::common::MMIODerefWrapper, ++ exception, ++ memory::{Address, Virtual}, +}; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, -@@ -60,12 +62,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. -@@ -75,10 +78,15 @@ +@@ -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: usize) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { -- registers: Registers::new(mmio_start_addr), -+ registers: InitStateLock::new(Registers::new(mmio_start_addr)), + registers: 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: -@@ -91,7 +99,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. -@@ -101,7 +111,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. -@@ -117,7 +129,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. -@@ -136,6 +149,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 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicd.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2/gicd.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicd.rs -@@ -8,8 +8,9 @@ +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, -- synchronization::IRQSafeNullLock, + bsp::device_driver::common::MMIODerefWrapper, ++ memory::{Address, Virtual}, + state, synchronization, -+ synchronization::{IRQSafeNullLock, InitStateLock}, + synchronization::IRQSafeNullLock, }; use tock_registers::{ - interfaces::{Readable, Writeable}, -@@ -83,7 +84,7 @@ - shared_registers: IRQSafeNullLock, - - /// Access to banked registers is unguarded. -- banked_registers: BankedRegisters, -+ banked_registers: InitStateLock, - } - - //-------------------------------------------------------------------------------------------------- -@@ -120,6 +121,7 @@ - //-------------------------------------------------------------------------------------------------- - // Public Code - //-------------------------------------------------------------------------------------------------- -+use crate::synchronization::interface::ReadWriteEx; - use synchronization::interface::Mutex; - - impl GICD { -@@ -131,10 +133,17 @@ - pub const unsafe fn new(mmio_start_addr: usize) -> Self { +@@ -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), -+ 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: -@@ -142,7 +151,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)) - } + banked_registers: BankedRegisters::new(mmio_start_addr), - /// Route all SPIs to the boot core and enable the distributor. -@@ -181,10 +191,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 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm/gicv2.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs -@@ -79,7 +79,8 @@ - mod gicc; - mod gicd; - --use crate::{bsp, cpu, driver, exception, synchronization, synchronization::InitStateLock}; -+use crate::{bsp, cpu, driver, exception, memory, synchronization, synchronization::InitStateLock}; -+use core::sync::atomic::{AtomicBool, Ordering}; +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 @@ - //-------------------------------------------------------------------------------------------------- - // Private Definitions -@@ -96,12 +97,18 @@ - - /// Representation of the GIC. - pub struct GICv2 { -+ gicd_mmio_descriptor: memory::mmu::MMIODescriptor, -+ gicc_mmio_descriptor: memory::mmu::MMIODescriptor, -+ - /// The Distributor. - gicd: gicd::GICD, - - /// The CPU Interface. - gicc: gicc::GICC, + use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, +- cpu, driver, exception, synchronization, ++ cpu, driver, exception, ++ memory::{Address, Virtual}, ++ synchronization, + synchronization::InitStateLock, + }; -+ /// 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 +125,17 @@ - /// +@@ -125,7 +127,10 @@ /// # Safety /// -- /// - The user must ensure to provide a correct MMIO start address. + /// - 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_mmio_descriptor: memory::mmu::MMIODescriptor, -+ gicc_mmio_descriptor: memory::mmu::MMIODescriptor, ++ 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), -+ gicd_mmio_descriptor, -+ gicc_mmio_descriptor, -+ gicd: gicd::GICD::new(gicd_mmio_descriptor.start_addr().as_usize()), -+ gicc: gicc::GICC::new(gicc_mmio_descriptor.start_addr().as_usize()), -+ is_mmio_remapped: AtomicBool::new(false), - handler_table: InitStateLock::new([None; Self::NUM_IRQS]), - } - } -@@ -139,6 +152,20 @@ - } + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), - unsafe fn init(&self) -> Result<(), &'static str> { -+ let remapped = self.is_mmio_remapped.load(Ordering::Relaxed); -+ if !remapped { -+ // GICD -+ let mut virt_addr = memory::mmu::kernel_map_mmio("GICD", &self.gicd_mmio_descriptor)?; -+ self.gicd.set_mmio(virt_addr.as_usize()); -+ -+ // GICC -+ virt_addr = memory::mmu::kernel_map_mmio("GICC", &self.gicc_mmio_descriptor)?; -+ self.gicc.set_mmio(virt_addr.as_usize()); -+ -+ // Conclude remapping. -+ self.is_mmio_remapped.store(true, Ordering::Relaxed); -+ } -+ - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { - self.gicd.boot_core_init(); - } - -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs -@@ -5,9 +5,10 @@ +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, synchronization, -+ bsp::device_driver::common::MMIODerefWrapper, driver, memory, synchronization, - synchronization::IRQSafeNullLock, +- 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 core::sync::atomic::{AtomicUsize, Ordering}; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, - register_bitfields, register_structs, -@@ -121,6 +122,8 @@ - - /// Representation of the GPIO HW. - pub struct GPIO { -+ mmio_descriptor: memory::mmu::MMIODescriptor, -+ virt_mmio_start_addr: AtomicUsize, - inner: IRQSafeNullLock, - } - -@@ -140,6 +143,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) { -@@ -194,10 +210,12 @@ +@@ -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. + /// - 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(mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { ++ pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { -- inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), -+ mmio_descriptor, -+ virt_mmio_start_addr: AtomicUsize::new(0), -+ inner: IRQSafeNullLock::new(GPIOInner::new(mmio_descriptor.start_addr().as_usize())), + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), } - } -@@ -216,4 +234,26 @@ - 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.mmio_descriptor)?; -+ -+ self.inner -+ .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; -+ -+ self.virt_mmio_start_addr -+ .store(virt_addr.as_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 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs -@@ -7,7 +7,7 @@ - use super::{InterruptController, PendingIRQs, PeripheralIRQ}; +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, -+ driver, exception, memory, synchronization, ++ exception, ++ memory::{Address, Virtual}, ++ synchronization, synchronization::{IRQSafeNullLock, InitStateLock}, }; use tock_registers::{ -@@ -55,11 +55,13 @@ - - /// Representation of the peripheral interrupt controller. - pub struct PeripheralIC { -+ mmio_descriptor: memory::mmu::MMIODescriptor, -+ - /// Access to write registers is guarded with a lock. - wo_registers: IRQSafeNullLock, +@@ -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; - /// Register read access is unguarded. -- ro_registers: ReadOnlyRegisters, -+ ro_registers: InitStateLock, +@@ -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), + } - /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. - handler_table: InitStateLock, -@@ -74,21 +76,26 @@ +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. + /// - 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(mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { -+ let addr = mmio_descriptor.start_addr().as_usize(); -+ ++ 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), -+ 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]), + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } - } - - /// 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) -+ }) - } - } -@@ -97,6 +104,24 @@ - //------------------------------------------------------------------------------ - use synchronization::interface::{Mutex, ReadWriteEx}; +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 @@ -+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.mmio_descriptor)?.as_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; + //! Common device driver code. ++use crate::memory::{Address, Virtual}; + use core::{fmt, marker::PhantomData, ops}; -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs -@@ -6,7 +6,7 @@ + //-------------------------------------------------------------------------------------------------- +@@ -11,7 +12,7 @@ + //-------------------------------------------------------------------------------------------------- - mod peripheral_ic; + pub struct MMIODerefWrapper { +- start_addr: usize, ++ start_addr: Address, + phantom: PhantomData T>, + } --use crate::{driver, exception}; -+use crate::{driver, exception, memory}; +@@ -25,7 +26,7 @@ - //-------------------------------------------------------------------------------------------------- - // 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( -+ _local_mmio_descriptor: memory::mmu::MMIODescriptor, -+ periph_mmio_descriptor: memory::mmu::MMIODescriptor, -+ ) -> Self { + impl MMIODerefWrapper { + /// Create an instance. +- pub const unsafe fn new(start_addr: usize) -> Self { ++ pub const unsafe fn new(start_addr: Address) -> Self { Self { -- periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), -+ periph: peripheral_ic::PeripheralIC::new(periph_mmio_descriptor), - } + 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 _) } } } -@@ -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 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs -@@ -10,10 +10,13 @@ - //! - - use crate::{ -- bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, -+ bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, memory, - synchronization, synchronization::IRQSafeNullLock, - }; --use core::fmt; -+use core::{ -+ fmt, -+ sync::atomic::{AtomicUsize, Ordering}, +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 tock_registers::{ - interfaces::{Readable, Writeable}, - register_bitfields, register_structs, -@@ -231,6 +234,8 @@ - - /// Representation of the UART. - pub struct PL011Uart { -+ mmio_descriptor: memory::mmu::MMIODescriptor, -+ virt_mmio_start_addr: AtomicUsize, - inner: IRQSafeNullLock, - irq_number: bsp::device_driver::IRQNumber, - } -@@ -270,7 +275,15 @@ - /// 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) { -+ /// -+ /// # 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); -+ } -+ - // 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. -@@ -312,6 +325,8 @@ - self.registers - .CR - .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); -+ -+ Ok(()) - } ++use core::{ ++ mem::MaybeUninit, ++ sync::atomic::{AtomicBool, Ordering}, + }; +-use core::sync::atomic::{AtomicBool, Ordering}; - /// Send a character. -@@ -389,13 +404,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, -+ mmio_descriptor: memory::mmu::MMIODescriptor, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { - Self { -- inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), -+ mmio_descriptor, -+ virt_mmio_start_addr: AtomicUsize::new(0), -+ inner: IRQSafeNullLock::new(PL011UartInner::new( -+ mmio_descriptor.start_addr().as_usize(), -+ )), - irq_number, - } - } -@@ -412,7 +432,13 @@ - } + //-------------------------------------------------------------------------------------------------- + // 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 + //-------------------------------------------------------------------------------------------------- - unsafe fn init(&self) -> Result<(), &'static str> { -- self.inner.lock(|inner| inner.init()); -+ let virt_addr = memory::mmu::kernel_map_mmio(self.compatible(), &self.mmio_descriptor)?; ++/// 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)?; + -+ self.inner -+ .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; ++ 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()); + -+ self.virt_mmio_start_addr -+ .store(virt_addr.as_usize(), Ordering::Relaxed); ++ 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(()) - } -@@ -431,6 +457,16 @@ + Ok(()) + } - 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(()) ++} + -+ fn virt_mmio_start_addr(&self) -> Option { -+ let addr = self.virt_mmio_start_addr.load(Ordering::Relaxed); ++/// 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, ++ )?; + -+ if addr == 0 { -+ return None; -+ } ++ INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); + -+ Some(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(()) } - impl console::interface::Write for PL011Uart { - -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/console.rs -+++ 14_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, driver}; - use core::fmt; + /// 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()); - //-------------------------------------------------------------------------------------------------- -@@ -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 driver::interface::DeviceDriver; - -+ let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START.as_usize()); -+ let mut panic_uart = -+ device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.as_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 + 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(()) + } -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/driver.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs -@@ -46,7 +46,15 @@ - &self.device_drivers[..] - } +-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 post_device_driver_init(&self) { -+ fn early_print_device_drivers(&self) -> &[&'static (dyn DeviceDriver + Sync)] { -+ &self.device_drivers[0..=1] -+ } +-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; + -+ 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(); - } ++ 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/src/bsp/raspberrypi/link.ld 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld +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) : @@ -1443,7 +1252,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld 14_vir /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ -@@ -68,6 +68,7 @@ +@@ -67,6 +67,7 @@ /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ @@ -1451,11 +1260,10 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld 14_vir .data : { *(.data*) } :segment_data /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ -@@ -78,4 +79,16 @@ - . = ALIGN(16); +@@ -78,6 +79,18 @@ __bss_end_exclusive = .; } :segment_data -+ + + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + @@ -1467,11 +1275,14 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/link.ld 14_vir + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") - } ++ + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs +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. @@ -1761,9 +1572,9 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory/mmu.rs + } } -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs +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. //! @@ -1843,7 +1654,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 14_v } //-------------------------------------------------------------------------------------------------- -@@ -50,35 +91,26 @@ +@@ -50,34 +91,23 @@ /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { @@ -1871,12 +1682,11 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 14_v 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 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; + @@ -1886,14 +1696,11 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 14_v + 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. -@@ -86,13 +118,22 @@ +@@ -85,13 +115,22 @@ pub mod mmio { use super::*; @@ -1922,7 +1729,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 14_v } //-------------------------------------------------------------------------------------------------- -@@ -105,15 +146,76 @@ +@@ -104,15 +143,76 @@ /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] @@ -1930,19 +1737,21 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 14_v - 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)] + /// # 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) } - } - --/// Exclusive end page address of the code segment. ++} ++ +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { @@ -1951,12 +1760,10 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 14_v + +/// Size of the data 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 } ++/// # 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) } +} @@ -2005,65 +1812,13 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/memory.rs 14_v + PageAddress::from(map::END) } -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs ---- 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi.rs -+++ 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs -@@ -10,17 +10,20 @@ - pub mod exception; - pub mod memory; +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 @@ -+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), -+ ) - }; - - //-------------------------------------------------------------------------------------------------- + //! General purpose code. -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/common.rs 14_virtual_mem_part2_mmio_remap/src/common.rs ---- 13_exceptions_part2_peripheral_IRQs/src/common.rs -+++ 14_virtual_mem_part2_mmio_remap/src/common.rs -@@ -0,0 +1,29 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2020-2022 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 { @@ -2087,91 +1842,56 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/common.rs 14_virtual_mem_part2 + + (value + alignment - 1) & !(alignment - 1) +} - -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/driver.rs 14_virtual_mem_part2_mmio_remap/src/driver.rs ---- 13_exceptions_part2_peripheral_IRQs/src/driver.rs -+++ 14_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); - } - } + /// 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/src/lib.rs 14_virtual_mem_part2_mmio_remap/src/lib.rs ---- 13_exceptions_part2_peripheral_IRQs/src/lib.rs -+++ 14_virtual_mem_part2_mmio_remap/src/lib.rs -@@ -111,8 +111,10 @@ - #![feature(asm_const)] +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] - // Testing -@@ -125,6 +127,7 @@ - mod synchronization; - - pub mod bsp; -+pub mod common; - pub mod console; - pub mod cpu; - pub mod driver; -@@ -177,6 +180,7 @@ +@@ -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::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); test_main(); -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/main.rs 14_virtual_mem_part2_mmio_remap/src/main.rs ---- 13_exceptions_part2_peripheral_IRQs/src/main.rs -+++ 14_virtual_mem_part2_mmio_remap/src/main.rs -@@ -25,21 +25,41 @@ +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 driver::interface::DriverManager; - use memory::mmu::interface::MMU; - +- exception::handling_init(); - if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { @@ -2183,131 +1903,32 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/main.rs 14_virtual_mem_part2_m + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); -+ } -+ // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. -+ -+ memory::mmu::post_enable_init(); -+ -+ // 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. -- for i in bsp::driver::driver_manager().all_device_drivers().iter() { -+ // 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 +86,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/src/memory/mmu/alloc.rs 14_virtual_mem_part2_mmio_remap/src/memory/mmu/alloc.rs ---- 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/alloc.rs -+++ 14_virtual_mem_part2_mmio_remap/src/memory/mmu/alloc.rs -@@ -0,0 +1,70 @@ -+// SPDX-License-Identifier: MIT OR Apache-2.0 -+// -+// Copyright (c) 2021-2022 Andre Richter -+ -+//! 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 initialize(&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"); -+ } ++ memory::mmu::post_enable_init(); + -+ self.pool -+ .as_mut() -+ .unwrap() -+ .take_first_n_pages(num_requested_pages) -+ } -+} + // 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/src/memory/mmu/mapping_record.rs 14_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs ---- 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs -+++ 14_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs -@@ -0,0 +1,233 @@ +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + @@ -2315,7 +1936,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs 1 + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; -+use crate::{bsp, info, synchronization, synchronization::InitStateLock, warn}; ++use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions @@ -2383,6 +2004,19 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs 1 + 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); @@ -2397,8 +2031,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs 1 + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() -+ .filter(|x| x.is_some()) -+ .map(|x| x.as_mut().unwrap()) ++ .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() { @@ -2428,13 +2061,13 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs 1 + phys_region, + attr, + )); ++ ++ self.sort(); ++ + Ok(()) + } + + pub fn print(&self) { -+ const KIB_RSHIFT: u32 = 10; // log2(1024). -+ const MIB_RSHIFT: u32 = 20; // log2(1024 * 1024). -+ + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", @@ -2449,13 +2082,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs 1 + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + -+ 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 (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", @@ -2474,8 +2101,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs 1 + }; + + info!( -+ " {}..{} --> {}..{} | \ -+ {: >3} {} | {: <3} {} {: <2} | {}", ++ " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, @@ -2539,9 +2165,84 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/mapping_record.rs 1 + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/translation_table.rs 14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs ---- 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/translation_table.rs -+++ 14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs +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; @@ -2636,13 +2337,13 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/translation_table.r + } +} -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs 14_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs ---- 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs -+++ 14_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs -@@ -0,0 +1,375 @@ +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-2022 Andre Richter ++// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + @@ -2657,13 +2358,13 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs 14_virtual +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. -+#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] ++#[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, PartialOrd, PartialEq)] ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, @@ -2671,7 +2372,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs 14_virtual + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] -+#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, @@ -2679,7 +2380,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs 14_virtual + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] -+#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, @@ -2687,7 +2388,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs 14_virtual + +/// Collection of memory attributes. +#[allow(missing_docs)] -+#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] ++#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, @@ -3005,22 +2706,20 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu/types.rs 14_virtual + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + -+ let mut count = 0; -+ for i in allocation.into_iter() { ++ for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( -+ i.into_inner().as_usize(), -+ count * bsp::memory::mmu::KernelGranule::SIZE ++ alloc.into_inner().as_usize(), ++ i * bsp::memory::mmu::KernelGranule::SIZE + ); -+ count = count + 1; + } + } +} -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs ---- 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs -+++ 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs -@@ -3,29 +3,24 @@ - // Copyright (c) 2020-2022 Andre Richter +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. -//! @@ -3038,11 +2737,12 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; -+mod alloc; +mod mapping_record; ++mod page_alloc; mod translation_table; +mod types; +-use crate::common; -use core::{fmt, ops::RangeInclusive}; +use crate::{ + bsp, @@ -3059,7 +2759,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p //-------------------------------------------------------------------------------------------------- // Public Definitions -@@ -45,13 +40,15 @@ +@@ -46,13 +40,15 @@ /// MMU functions. pub trait MMU { @@ -3078,7 +2778,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p /// Returns true if the MMU is enabled, false otherwise. fn is_enabled(&self) -> bool; -@@ -64,55 +61,51 @@ +@@ -65,55 +61,51 @@ /// Describes properties of an address space. pub struct AddressSpace; @@ -3141,7 +2841,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p +fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + -+ alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.initialize(region)); ++ page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Map a region in the kernel's translation tables. @@ -3175,7 +2875,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p } //-------------------------------------------------------------------------------------------------- -@@ -132,6 +125,9 @@ +@@ -133,6 +125,9 @@ /// The granule's size. pub const SIZE: usize = Self::size_checked(); @@ -3185,7 +2885,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p /// The granule's shift, aka log2(size). pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; -@@ -159,110 +155,147 @@ +@@ -160,98 +155,147 @@ } } @@ -3224,31 +2924,42 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p - 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) = common::size_human_readable_ceil(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") -- }; -+ kernel_map_at_unchecked(name, virt_region, phys_region, attr)?; - - let attr = match self.attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => "C", - MemAttributes::Device => "Dev", - }; -+ Ok(()) -+} - +- - 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. @@ -3273,22 +2984,29 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, - }; ++ }; -- let xn = if self.attribute_fields.execute_never { -- "PXN" -- } else { -- "PX" -- }; +- /// 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 = -+ alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; ++ page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; -- write!( -- f, -- " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", -- start, end, size, unit, attr, acc_p, xn, self.name -- ) -- } +- 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, @@ -3342,37 +3060,8 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() - } ++} --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)); - } - } @@ -3400,7 +3089,7 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p + 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 = alloc::kernel_mmio_va_allocator() ++ let virt_region = page_alloc::kernel_mmio_va_allocator() + .lock(|allocator| allocator.alloc(num_pages)) + .unwrap(); @@ -3426,9 +3115,9 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory/mmu.rs 14_virtual_mem_p } } -diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory.rs 14_virtual_mem_part2_mmio_remap/src/memory.rs ---- 13_exceptions_part2_peripheral_IRQs/src/memory.rs -+++ 14_virtual_mem_part2_mmio_remap/src/memory.rs +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. @@ -3446,18 +3135,18 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory.rs 14_virtual_mem_part2 +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. -+pub trait AddressType: Copy + Clone + PartialOrd + PartialEq {} ++pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. -+#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] ++#[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)] ++#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. -+#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] ++#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, @@ -3588,24 +3277,82 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/src/memory.rs 14_virtual_mem_part2 + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + -+ assert_eq!(addr.is_page_aligned(), false); ++ assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} -diff -uNr 13_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs 14_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs ---- 13_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault.rs -+++ 14_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs -@@ -21,18 +21,40 @@ +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 memory::mmu::interface::MMU; -+ use libkernel::driver::interface::DriverManager; + 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::console::qemu_bring_up_console(); +- 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"); @@ -3624,37 +3371,25 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/tests/02_exception_sync_page_fault + info!("Enabling MMU failed: {}", e); cpu::qemu_exit_failure() } -+ // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. -+ + + memory::mmu::post_enable_init(); -+ bsp::console::qemu_bring_up_console(); ++ bsp::driver::qemu_bring_up_console(); + -+ // 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. - 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/tests/03_exception_restore_sanity.rs 14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rs ---- 13_exceptions_part2_peripheral_IRQs/tests/03_exception_restore_sanity.rs -+++ 14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rs -@@ -30,18 +30,40 @@ +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; -+ use libkernel::driver::interface::DriverManager; - +- exception::handling_init(); -- bsp::console::qemu_bring_up_console(); +- bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); @@ -3673,22 +3408,44 @@ diff -uNr 13_exceptions_part2_peripheral_IRQs/tests/03_exception_restore_sanity. + info!("Enabling MMU failed: {}", e); cpu::qemu_exit_failure() } -+ // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. -+ + + memory::mmu::post_enable_init(); -+ bsp::console::qemu_bring_up_console(); ++ bsp::driver::qemu_bring_up_console(); + -+ // 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()); + 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); + } -+ bsp::driver::driver_manager().post_early_print_device_driver_init(); -+ // Printing available again from here on. ++ ++ memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); - info!("Making a dummy system call"); +- 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 00000000..b85ecbed --- /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/build.rs b/14_virtual_mem_part2_mmio_remap/kernel/build.rs similarity index 100% rename from 14_virtual_mem_part2_mmio_remap/build.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/build.rs diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu.rs similarity index 93% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu.rs index 66da661c..2d010473 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/boot.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs similarity index 92% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/boot.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs index f677c9c4..c80f3ebb 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/boot.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,12 +11,16 @@ //! //! crate::cpu::boot::arch_boot +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; -use cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Private Code diff --git a/12_integrated_testing/src/_arch/aarch64/cpu/boot.s b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s similarity index 85% rename from 12_integrated_testing/src/_arch/aarch64/cpu/boot.s rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s index 28b35087..f6df2123 100644 --- a/12_integrated_testing/src/_arch/aarch64/cpu/boot.s +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s @@ -18,9 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _EL2, 0x8 -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -32,12 +29,12 @@ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL - cmp x0, _EL2 + 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, _core_id_mask + 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 @@ -60,6 +57,14 @@ _start: 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 diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/smp.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/smp.rs similarity index 88% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/smp.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/smp.rs index 351fde62..49192038 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/smp.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/smp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural symmetric multiprocessing. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::smp::arch_smp -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.rs similarity index 88% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.rs index 495dba34..73019800 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! @@ -11,9 +11,9 @@ //! //! crate::exception::arch_exception -use crate::{bsp, exception}; +use crate::exception; +use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::InMemoryRegister, @@ -46,7 +46,7 @@ struct ExceptionContext { /// Saved program status. spsr_el1: SpsrEL1, - // Exception syndrome register. + /// Exception syndrome register. esr_el1: EsrEL1, } @@ -68,17 +68,17 @@ fn default_exception_handler(exc: &ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } @@ -87,7 +87,7 @@ unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { #[cfg(feature = "test_build")] { const TEST_SVC_ID: u64 = 0x1337; @@ -103,15 +103,13 @@ unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { } #[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); +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] -unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -120,17 +118,17 @@ unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -139,17 +137,17 @@ unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.s b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.s similarity index 97% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.s rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.s index 5aae30b9..91805ee7 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/exception.s +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.s @@ -9,6 +9,7 @@ /// 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 @@ -47,6 +48,9 @@ // 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 diff --git a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/exception/asynchronous.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception/asynchronous.rs similarity index 79% rename from 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/exception/asynchronous.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception/asynchronous.rs index 73b82e65..811ef138 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/exception/asynchronous.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! @@ -11,8 +11,8 @@ //! //! crate::exception::asynchronous::arch_asynchronous +use aarch64_cpu::registers::*; use core::arch::asm; -use cortex_a::registers::*; use tock_registers::interfaces::{Readable, Writeable}; //-------------------------------------------------------------------------------------------------- @@ -83,42 +83,32 @@ pub fn is_local_irq_masked() -> bool { /// /// "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) - ); +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. -/// -/// # 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) - ); +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). -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. #[inline(always)] -pub unsafe fn local_irq_mask_save() -> u64 { +pub fn local_irq_mask_save() -> u64 { let saved = DAIF.get(); local_irq_mask(); @@ -127,12 +117,11 @@ pub unsafe fn local_irq_mask_save() -> u64 { /// Restore the interrupt mask bits (DAIF) using the callee's argument. /// -/// # Safety +/// # Invariant /// -/// - Changes the HW state of the executing core. /// - No sanity checks on the input. #[inline(always)] -pub unsafe fn local_irq_restore(saved: u64) { +pub fn local_irq_restore(saved: u64) { DAIF.set(saved); } diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs similarity index 98% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs index e2db2d23..e0717a7f 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! @@ -17,8 +17,8 @@ use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical}, }; +use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu/translation_table.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs similarity index 99% rename from 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu/translation_table.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs index cc31b302..2d87543c 100644 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu/translation_table.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! 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 00000000..ee1c3ef7 --- /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/src/bsp.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp.rs similarity index 81% rename from 14_virtual_mem_part2_mmio_remap/src/bsp.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp.rs index 824787f6..246973bc 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver.rs similarity index 82% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver.rs index eafaf775..2dfaec8d 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm.rs similarity index 64% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm.rs index e83e24c9..8d1cbfbd 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver/arm.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm/gicv2.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs similarity index 78% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm/gicv2.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs index 4c68a692..256de704 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm/gicv2.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICv2 Driver - ARM Generic Interrupt Controller v2. //! @@ -79,36 +79,36 @@ mod gicc; mod gicd; -use crate::{bsp, cpu, driver, exception, memory, synchronization, synchronization::InitStateLock}; -use core::sync::atomic::{AtomicBool, Ordering}; +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- -type HandlerTable = [Option; GICv2::NUM_IRQS]; +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; /// Representation of the GIC. pub struct GICv2 { - gicd_mmio_descriptor: memory::mmu::MMIODescriptor, - gicc_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, } @@ -119,24 +119,22 @@ pub struct GICv2 { 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; + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; /// Create an instance. /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. + /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new( - gicd_mmio_descriptor: memory::mmu::MMIODescriptor, - gicc_mmio_descriptor: memory::mmu::MMIODescriptor, + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, ) -> Self { Self { - gicd_mmio_descriptor, - gicc_mmio_descriptor, - gicd: gicd::GICD::new(gicd_mmio_descriptor.start_addr().as_usize()), - gicc: gicc::GICC::new(gicc_mmio_descriptor.start_addr().as_usize()), - is_mmio_remapped: AtomicBool::new(false), - handler_table: InitStateLock::new([None; Self::NUM_IRQS]), + 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]), } } } @@ -147,25 +145,13 @@ impl GICv2 { use synchronization::interface::ReadWriteEx; impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "GICv2 (ARM Generic Interrupt Controller v2)" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { - let remapped = self.is_mmio_remapped.load(Ordering::Relaxed); - if !remapped { - // GICD - let mut virt_addr = memory::mmu::kernel_map_mmio("GICD", &self.gicd_mmio_descriptor)?; - self.gicd.set_mmio(virt_addr.as_usize()); - - // GICC - virt_addr = memory::mmu::kernel_map_mmio("GICC", &self.gicc_mmio_descriptor)?; - self.gicc.set_mmio(virt_addr.as_usize()); - - // Conclude remapping. - self.is_mmio_remapped.store(true, Ordering::Relaxed); - } - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { self.gicd.boot_core_init(); } @@ -182,23 +168,22 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { - let irq_number = irq_number.get(); + let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } - table[irq_number] = Some(descriptor); + table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } - fn enable(&self, irq_number: Self::IRQNumberType) { + fn enable(&self, irq_number: &Self::IRQNumberType) { self.gicd.enable(irq_number); } @@ -221,7 +206,7 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { 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"); + descriptor.handler().handle().expect("Error handling IRQ"); } } }); @@ -238,7 +223,7 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { 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); + info!(" {: >3}. {}", i + 32, handler.name()); } } }); diff --git a/16_virtual_mem_part4_higher_half_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 similarity index 79% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/arm/gicv2/gicc.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs index 1a151d24..0fd16bb3 100644 --- a/16_virtual_mem_part4_higher_half_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 @@ -1,11 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICC Driver - GIC CPU interface. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, exception, synchronization::InitStateLock, + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, }; use tock_registers::{ interfaces::{Readable, Writeable}, @@ -62,13 +64,12 @@ type Registers = MMIODerefWrapper; /// Representation of the GIC CPU interface. pub struct GICC { - registers: InitStateLock, + registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -use crate::synchronization::interface::ReadWriteEx; impl GICC { /// Create an instance. @@ -76,17 +77,12 @@ impl GICC { /// # 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: InitStateLock::new(Registers::new(mmio_start_addr)), + registers: 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: @@ -99,9 +95,7 @@ impl GICC { /// - 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. - }); + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. } /// Enable the interface - start accepting IRQs. @@ -111,9 +105,7 @@ impl GICC { /// - 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); - }); + self.registers.CTLR.write(CTLR::Enable::SET); } /// Extract the number of the highest-priority pending IRQ. @@ -129,8 +121,7 @@ impl GICC { &self, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) -> usize { - self.registers - .read(|regs| regs.IAR.read(IAR::InterruptID) as usize) + self.registers.IAR.read(IAR::InterruptID) as usize } /// Complete handling of the currently active IRQ. @@ -149,8 +140,6 @@ impl GICC { irq_number: u32, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) { - self.registers.read(|regs| { - regs.EOIR.write(EOIR::EOIINTID.val(irq_number)); - }); + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); } } diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm/gicv2/gicd.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs similarity index 85% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm/gicv2/gicd.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs index 60bbc468..1fc9d70e 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm/gicv2/gicd.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICD Driver - GIC Distributor. //! @@ -9,8 +9,9 @@ use crate::{ bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, state, synchronization, - synchronization::{IRQSafeNullLock, InitStateLock}, + synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{Readable, Writeable}, @@ -51,9 +52,9 @@ register_structs! { (0x004 => TYPER: ReadOnly), (0x008 => _reserved1), (0x104 => ISENABLER: [ReadWrite; 31]), - (0x108 => _reserved2), + (0x180 => _reserved2), (0x820 => ITARGETSR: [ReadWrite; 248]), - (0x824 => @END), + (0xC00 => @END), } } @@ -64,7 +65,7 @@ register_structs! { (0x100 => ISENABLER: ReadWrite), (0x104 => _reserved2), (0x800 => ITARGETSR: [ReadOnly; 8]), - (0x804 => @END), + (0x820 => @END), } } @@ -84,7 +85,7 @@ pub struct GICD { shared_registers: IRQSafeNullLock, /// Access to banked registers is unguarded. - banked_registers: InitStateLock, + banked_registers: BankedRegisters, } //-------------------------------------------------------------------------------------------------- @@ -121,7 +122,6 @@ impl SharedRegisters { //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -use crate::synchronization::interface::ReadWriteEx; use synchronization::interface::Mutex; impl GICD { @@ -130,20 +130,13 @@ impl GICD { /// # 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: InitStateLock::new(BankedRegisters::new(mmio_start_addr)), + banked_registers: 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: @@ -151,8 +144,7 @@ impl GICD { /// "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)) + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) } /// Route all SPIs to the boot core and enable the distributor. @@ -180,7 +172,7 @@ impl GICD { } /// Enable an interrupt. - pub fn enable(&self, irq_num: super::IRQNumber) { + 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 @@ -191,10 +183,10 @@ impl GICD { // 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; + 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; diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm.rs similarity index 83% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm.rs index 5a7cc23b..7b7c288b 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs similarity index 76% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs index eea07b75..812156f4 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -1,14 +1,17 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, memory, synchronization, + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, synchronization::IRQSafeNullLock, }; -use core::sync::atomic::{AtomicUsize, Ordering}; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, @@ -109,26 +112,21 @@ 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 { - mmio_descriptor: memory::mmu::MMIODescriptor, - virt_mmio_start_addr: AtomicUsize, inner: IRQSafeNullLock, } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -137,29 +135,16 @@ impl GPIOInner { /// # 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), } } - /// 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 crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. @@ -205,17 +190,21 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new(mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { - mmio_descriptor, - virt_mmio_start_addr: AtomicUsize::new(0), - inner: IRQSafeNullLock::new(GPIOInner::new(mmio_descriptor.start_addr().as_usize())), + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), } } @@ -231,29 +220,9 @@ impl GPIO { 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.mmio_descriptor)?; + type IRQNumberType = IRQNumber; - self.inner - .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; - - self.virt_mmio_start_addr - .store(virt_addr.as_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) + fn compatible(&self) -> &'static str { + Self::COMPATIBLE } } diff --git a/14_virtual_mem_part2_mmio_remap/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 similarity index 62% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs index 99961fac..62f07800 100644 --- a/14_virtual_mem_part2_mmio_remap/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 @@ -1,12 +1,18 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Interrupt Controller Driver. mod peripheral_ic; -use crate::{driver, exception, memory}; +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -21,13 +27,12 @@ struct PendingIRQs { // Public Definitions //-------------------------------------------------------------------------------------------------- -pub type LocalIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -pub type PeripheralIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; +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), @@ -52,16 +57,13 @@ impl Iterator for PendingIRQs { type Item = usize; fn next(&mut self) -> Option { - use core::intrinsics::cttz; - - let next = cttz(self.bitmask); - if next == 64 { + if self.bitmask == 0 { return None; } - self.bitmask &= !(1 << next); - - Some(next as usize) + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) } } @@ -69,22 +71,30 @@ impl Iterator for PendingIRQs { // 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 { - const MAX_LOCAL_IRQ_NUMBER: usize = 11; + // 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; - const NUM_PERIPHERAL_IRQS: usize = Self::MAX_PERIPHERAL_IRQ_NUMBER + 1; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; /// Create an instance. /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new( - _local_mmio_descriptor: memory::mmu::MMIODescriptor, - periph_mmio_descriptor: memory::mmu::MMIODescriptor, - ) -> Self { + /// - 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_descriptor), + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), } } } @@ -94,12 +104,10 @@ impl InterruptController { //------------------------------------------------------------------------------ impl driver::interface::DeviceDriver for InterruptController { - fn compatible(&self) -> &'static str { - "BCM Interrupt Controller" - } + type IRQNumberType = IRQNumber; - unsafe fn init(&self) -> Result<(), &'static str> { - self.periph.init() + fn compatible(&self) -> &'static str { + Self::COMPATIBLE } } @@ -108,16 +116,23 @@ impl exception::asynchronous::interface::IRQManager for InterruptController { fn register_handler( &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { - match irq { + match irq_handler_descriptor.number() { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), - IRQNumber::Peripheral(pirq) => self.periph.register_handler(pirq, 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) { + fn enable(&self, irq: &Self::IRQNumberType) { match irq { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), diff --git a/14_virtual_mem_part2_mmio_remap/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 similarity index 69% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs index f09da862..a26bff8d 100644 --- a/14_virtual_mem_part2_mmio_remap/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 @@ -1,13 +1,19 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - -use super::{InterruptController, PendingIRQs, PeripheralIRQ}; +use super::{PendingIRQs, PeripheralIRQ}; use crate::{ bsp::device_driver::common::MMIODerefWrapper, - driver, exception, memory, synchronization, + exception, + memory::{Address, Virtual}, + synchronization, synchronization::{IRQSafeNullLock, InitStateLock}, }; use tock_registers::{ @@ -26,7 +32,7 @@ register_structs! { (0x00 => _reserved1), (0x10 => ENABLE_1: WriteOnly), (0x14 => ENABLE_2: WriteOnly), - (0x24 => @END), + (0x18 => @END), } } @@ -46,8 +52,8 @@ type WriteOnlyRegisters = MMIODerefWrapper; /// Abstraction for the ReadOnly parts of the associated MMIO registers. type ReadOnlyRegisters = MMIODerefWrapper; -type HandlerTable = - [Option; InterruptController::NUM_PERIPHERAL_IRQS]; +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -55,13 +61,11 @@ type HandlerTable = /// Representation of the peripheral interrupt controller. pub struct PeripheralIC { - 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, + ro_registers: ReadOnlyRegisters, /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. handler_table: InitStateLock, @@ -76,26 +80,21 @@ impl PeripheralIC { /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new(mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { - let addr = mmio_descriptor.start_addr().as_usize(); - + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { - 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]), + 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 { - self.ro_registers.read(|regs| { - let pending_mask: u64 = - (u64::from(regs.PENDING_2.get()) << 32) | u64::from(regs.PENDING_1.get()); + 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) - }) + PendingIRQs::new(pending_mask) } } @@ -104,46 +103,27 @@ impl PeripheralIC { //------------------------------------------------------------------------------ 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.mmio_descriptor)?.as_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, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { - let irq_number = irq.get(); + let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } - table[irq_number] = Some(descriptor); + table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } - fn enable(&self, irq: Self::IRQNumberType) { + fn enable(&self, irq: &Self::IRQNumberType) { self.wo_registers.lock(|regs| { let enable_reg = if irq.get() <= 31 { ®s.ENABLE_1 @@ -169,7 +149,7 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { 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"); + descriptor.handler().handle().expect("Error handling IRQ"); } } } @@ -184,7 +164,7 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { self.handler_table.read(|table| { for (i, opt) in table.iter().enumerate() { if let Some(handler) = opt { - info!(" {: >3}. {}", i, handler.name); + info!(" {: >3}. {}", i, handler.name()); } } }); diff --git a/16_virtual_mem_part4_higher_half_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 similarity index 86% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs index 23c09a7f..b424d4be 100644 --- a/16_virtual_mem_part4_higher_half_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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -10,13 +10,14 @@ //! - use crate::{ - bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, memory, - synchronization, synchronization::IRQSafeNullLock, -}; -use core::{ - fmt, - sync::atomic::{AtomicUsize, Ordering}, + 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, @@ -219,29 +220,23 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { - mmio_descriptor: memory::mmu::MMIODescriptor, - virt_mmio_start_addr: AtomicUsize, inner: IRQSafeNullLock, - irq_number: bsp::device_driver::IRQNumber, } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -250,7 +245,7 @@ impl PL011UartInner { /// # 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, @@ -275,15 +270,7 @@ impl PL011UartInner { /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. - /// - /// # 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); - } - + 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. @@ -325,8 +312,6 @@ impl PL011UartInner { self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - - Ok(()) } /// Send a character. @@ -399,24 +384,21 @@ 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 correct MMIO descriptors. - /// - The user must ensure to provide correct IRQ numbers. - pub const unsafe fn new( - mmio_descriptor: memory::mmu::MMIODescriptor, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { - mmio_descriptor, - virt_mmio_start_addr: AtomicUsize::new(0), - inner: IRQSafeNullLock::new(PL011UartInner::new( - mmio_descriptor.start_addr().as_usize(), - )), - irq_number, + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } } } @@ -427,46 +409,31 @@ impl PL011Uart { use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "BCM PL011 UART" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { - let virt_addr = memory::mmu::kernel_map_mmio(self.compatible(), &self.mmio_descriptor)?; - - self.inner - .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; - - self.virt_mmio_start_addr - .store(virt_addr.as_usize(), Ordering::Relaxed); + 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}; + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; - let descriptor = IRQDescriptor { - name: "BCM PL011 UART", - handler: self, - }; + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); - irq_manager().register_handler(self.irq_number, descriptor)?; - irq_manager().enable(self.irq_number); + irq_manager().register_handler(descriptor)?; + irq_manager().enable(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 { @@ -477,7 +444,7 @@ 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)) } @@ -514,6 +481,8 @@ impl console::interface::Statistics for PL011Uart { } } +impl console::interface::All for PL011Uart {} + impl exception::asynchronous::interface::IRQHandler for PL011Uart { fn handle(&self) -> Result<(), &'static str> { self.inner.lock(|inner| { 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 00000000..3ce1d8d8 --- /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 00000000..30421dfa --- /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/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/cpu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/cpu.rs similarity index 87% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/cpu.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/cpu.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. 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 00000000..a1f55b17 --- /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/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/exception.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception.rs similarity index 67% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/exception.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception.rs index aa6c5a63..a9eaa6ac 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/exception.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception/asynchronous.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs similarity index 56% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception/asynchronous.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs index dc5ab421..776182fd 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/exception/asynchronous.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -1,15 +1,18 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! BSP asynchronous exception handling. -use crate::{bsp, exception}; +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}; @@ -23,14 +26,3 @@ pub(in crate::bsp) mod irq_map { 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_part3_precomputed_tables/src/bsp/raspberrypi/link.ld b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld similarity index 90% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld index 717d817e..3f5f7043 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld @@ -3,8 +3,6 @@ * Copyright (c) 2018-2022 Andre Richter */ -INCLUDE kernel_virt_addr_space_size.ld; - PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; @@ -62,7 +60,6 @@ SECTIONS } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; @@ -93,4 +90,12 @@ SECTIONS __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/src/bsp/raspberrypi/memory.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs similarity index 97% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs index 660409bb..0d963aa3 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! @@ -107,9 +107,6 @@ pub(super) mod map { 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 --git a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs similarity index 99% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs index 8d395a58..86a118c3 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. diff --git a/15_virtual_mem_part3_precomputed_tables/src/common.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/common.rs similarity index 54% rename from 15_virtual_mem_part3_precomputed_tables/src/common.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/common.rs index 678f4a6c..2ad7e4c1 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/common.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! General purpose code. @@ -27,3 +27,20 @@ pub const fn align_up(value: usize, alignment: usize) -> usize { (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/src/console.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/console.rs similarity index 52% rename from 14_virtual_mem_part2_mmio_remap/src/console.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/console.rs index e49e241f..f0363464 100644 --- a/14_virtual_mem_part2_mmio_remap/src/console.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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: 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 00000000..e92a022b --- /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/16_virtual_mem_part4_higher_half_kernel/src/cpu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu.rs similarity index 89% rename from 16_virtual_mem_part4_higher_half_kernel/src/cpu.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/cpu.rs index e1493d1d..8716a918 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/cpu.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/14_virtual_mem_part2_mmio_remap/src/cpu/boot.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/boot.rs similarity index 71% rename from 14_virtual_mem_part2_mmio_remap/src/cpu/boot.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/14_virtual_mem_part2_mmio_remap/src/cpu/boot.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/14_virtual_mem_part2_mmio_remap/src/cpu/smp.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/smp.rs similarity index 87% rename from 14_virtual_mem_part2_mmio_remap/src/cpu/smp.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/cpu/smp.rs index 57386f79..de612d58 100644 --- a/14_virtual_mem_part2_mmio_remap/src/cpu/smp.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/cpu/smp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Symmetric multiprocessing. 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 00000000..2edf8b85 --- /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/15_virtual_mem_part3_precomputed_tables/src/exception.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/exception.rs similarity index 94% rename from 15_virtual_mem_part3_precomputed_tables/src/exception.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/exception.rs index f4af8144..3d5f219f 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/exception.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. @@ -21,7 +21,7 @@ pub use arch_exception::{current_privilege_level, handling_init}; /// Kernel privilege levels. #[allow(missing_docs)] -#[derive(PartialEq)] +#[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, diff --git a/13_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous.rs similarity index 63% rename from 13_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous.rs index fb1785c2..2c874dd6 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/exception/asynchronous.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous.rs @@ -1,14 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// 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 core::{fmt, marker::PhantomData}; +use crate::{bsp, synchronization}; +use core::marker::PhantomData; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports @@ -22,14 +24,23 @@ pub use arch_asynchronous::{ // Public Definitions //-------------------------------------------------------------------------------------------------- +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + /// Interrupt descriptor. #[derive(Copy, Clone)] -pub struct IRQDescriptor { +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + /// Descriptive name. - pub name: &'static str, + name: &'static str, /// Reference to handler trait object. - pub handler: &'static (dyn interface::IRQHandler + Sync), + handler: &'static (dyn interface::IRQHandler + Sync), } /// IRQContext token. @@ -59,17 +70,16 @@ pub mod interface { /// platform's interrupt controller. pub trait IRQManager { /// The IRQ number type depends on the implementation. - type IRQNumberType; + type IRQNumberType: Copy; /// Register a handler. fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: super::IRQDescriptor, + irq_handler_descriptor: super::IRQHandlerDescriptor, ) -> Result<(), &'static str>; /// Enable an interrupt in the controller. - fn enable(&self, irq_number: Self::IRQNumberType); + fn enable(&self, irq_number: &Self::IRQNumberType); /// Handle pending interrupts. /// @@ -85,17 +95,55 @@ pub mod interface { ); /// Print list of registered handlers. - fn print_handler(&self); + fn print_handler(&self) {} } } -/// A wrapper type for IRQ numbers with integrated range sanity check. -#[derive(Copy, Clone)] -pub struct IRQNumber(usize); +//-------------------------------------------------------------------------------------------------- +// 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. @@ -114,39 +162,29 @@ impl<'irq_context> IRQContext<'irq_context> { } } -impl IRQNumber<{ 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 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); - } + 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 00000000..38919ffe --- /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 00000000..fef85dfb --- /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/src/main.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/main.rs similarity index 56% rename from 14_virtual_mem_part2_mmio_remap/src/main.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs index b891492a..b76b003c 100644 --- a/14_virtual_mem_part2_mmio_remap/src/main.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. @@ -11,7 +13,7 @@ #![no_main] #![no_std] -use libkernel::{bsp, cpu, driver, exception, info, memory, state, time, warn}; +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; /// Early init code. /// @@ -24,8 +26,6 @@ use libkernel::{bsp, cpu, driver, exception, info, memory, state, time, warn}; /// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - exception::handling_init(); let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { @@ -36,37 +36,16 @@ unsafe fn kernel_init() -> ! { if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { panic!("Enabling MMU failed: {}", e); } - // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. memory::mmu::post_enable_init(); - // 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); - } + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", 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); - } - } + // Initialize all device drivers. + driver::driver_manager().init_drivers_and_irqs(); // Unmask interrupts on the boot CPU core. exception::asynchronous::local_irq_unmask(); @@ -80,9 +59,6 @@ unsafe fn kernel_init() -> ! { /// The main function running after the early init. fn kernel_main() -> ! { - use driver::interface::DriverManager; - use exception::asynchronous::interface::IRQManager; - info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); @@ -101,16 +77,10 @@ fn kernel_main() -> ! { ); info!("Drivers loaded:"); - for (i, driver) in bsp::driver::driver_manager() - .all_device_drivers() - .iter() - .enumerate() - { - info!(" {}. {}", i + 1, driver.compatible()); - } + driver::driver_manager().enumerate(); info!("Registered IRQ handlers:"); - bsp::exception::asynchronous::irq_manager().print_handler(); + exception::asynchronous::irq_manager().print_handler(); info!("Echoing input now"); cpu::wait_forever(); diff --git a/15_virtual_mem_part3_precomputed_tables/src/memory.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs similarity index 92% rename from 15_virtual_mem_part3_precomputed_tables/src/memory.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs index b5aa666d..b2638470 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/memory.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management. @@ -18,18 +18,18 @@ use core::{ //-------------------------------------------------------------------------------------------------- /// Metadata trait for marking the type of an address. -pub trait AddressType: Copy + Clone + PartialOrd + PartialEq {} +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} /// Zero-sized type to mark a physical address. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[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)] +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub enum Virtual {} /// Generic address type. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub struct Address { value: usize, _address_type: PhantomData ATYPE>, @@ -160,7 +160,7 @@ mod tests { bsp::memory::mmu::KernelGranule::SIZE * 2 ); - assert_eq!(addr.is_page_aligned(), false); + assert!(!addr.is_page_aligned()); assert_eq!(addr.offset_into_page(), 100); } diff --git a/14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs similarity index 96% rename from 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs index b0616f88..20e35def 100644 --- a/14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. @@ -8,8 +8,8 @@ #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; -mod alloc; mod mapping_record; +mod page_alloc; mod translation_table; mod types; @@ -81,7 +81,7 @@ use translation_table::interface::TranslationTable; fn kernel_init_mmio_va_allocator() { let region = bsp::memory::mmu::virt_mmio_remap_region(); - alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.initialize(region)); + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); } /// Map a region in the kernel's translation tables. @@ -205,7 +205,7 @@ pub unsafe fn kernel_map_mmio( }; let virt_region = - alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; kernel_map_at_unchecked( name, @@ -281,7 +281,7 @@ mod tests { 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 = alloc::kernel_mmio_va_allocator() + let virt_region = page_alloc::kernel_mmio_va_allocator() .lock(|allocator| allocator.alloc(num_pages)) .unwrap(); diff --git a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/mapping_record.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs similarity index 90% rename from 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/mapping_record.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs index d171c6e6..0e079220 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/mapping_record.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! A record of mapped pages. @@ -8,7 +8,7 @@ use super::{ AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, Physical, Virtual, }; -use crate::{bsp, info, synchronization, synchronization::InitStateLock, warn}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -76,6 +76,19 @@ impl MappingRecord { 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); @@ -90,8 +103,7 @@ impl MappingRecord { ) -> Option<&mut MappingRecordEntry> { self.inner .iter_mut() - .filter(|x| x.is_some()) - .map(|x| x.as_mut().unwrap()) + .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() { @@ -121,13 +133,13 @@ impl MappingRecord { phys_region, attr, )); + + self.sort(); + Ok(()) } pub fn print(&self) { - const KIB_RSHIFT: u32 = 10; // log2(1024). - const MIB_RSHIFT: u32 = 20; // log2(1024 * 1024). - info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); info!( " {:^44} {:^30} {:^7} {:^9} {:^35}", @@ -142,13 +154,7 @@ impl MappingRecord { let phys_start = i.phys_start_addr; let phys_end_inclusive = phys_start + (size - 1); - 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 (size, unit) = common::size_human_readable_ceil(size); let attr = match i.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", @@ -167,8 +173,7 @@ impl MappingRecord { }; info!( - " {}..{} --> {}..{} | \ - {: >3} {} | {: <3} {} {: <2} | {}", + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", virt_start, virt_end_inclusive, phys_start, diff --git a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/alloc.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs similarity index 93% rename from 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/alloc.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs index aadb72ef..344afd20 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/alloc.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter -//! Allocation. +//! Page allocation. use super::MemoryRegion; use crate::{ @@ -44,7 +44,7 @@ impl PageAllocator { } /// Initialize the allocator. - pub fn initialize(&mut self, pool: MemoryRegion) { + pub fn init(&mut self, pool: MemoryRegion) { if self.pool.is_some() { warn!("Already initialized"); return; diff --git a/14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs similarity index 98% rename from 14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs index 7eb46ebf..0445ab29 100644 --- a/14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Translation table. diff --git a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu/types.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs similarity index 95% rename from 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/types.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs index 82d5009c..8feee064 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu/types.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit types. @@ -15,13 +15,13 @@ use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; //-------------------------------------------------------------------------------------------------- /// A wrapper type around [Address] that ensures page alignment. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[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, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct MemoryRegion { start: PageAddress, end_exclusive: PageAddress, @@ -29,7 +29,7 @@ pub struct MemoryRegion { /// Architecture agnostic memory attributes. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum MemAttributes { CacheableDRAM, Device, @@ -37,7 +37,7 @@ pub enum MemAttributes { /// Architecture agnostic access permissions. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum AccessPermissions { ReadOnly, ReadWrite, @@ -45,7 +45,7 @@ pub enum AccessPermissions { /// Collection of memory attributes. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, @@ -363,13 +363,11 @@ mod tests { assert_eq!(allocation.num_pages(), 2); assert_eq!(three_region.num_pages(), 1); - let mut count = 0; - for i in allocation.into_iter() { + for (i, alloc) in allocation.into_iter().enumerate() { assert_eq!( - i.into_inner().as_usize(), - count * bsp::memory::mmu::KernelGranule::SIZE + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE ); - count = count + 1; } } } diff --git a/13_exceptions_part2_peripheral_IRQs/src/panic_wait.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/panic_wait.rs similarity index 78% rename from 13_exceptions_part2_peripheral_IRQs/src/panic_wait.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/panic_wait.rs index 08d7d453..c6f3a9c7 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/panic_wait.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/panic_wait.rs @@ -1,22 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. -use crate::{bsp, cpu, exception}; -use core::{fmt, panic::PanicInfo}; +use crate::{cpu, exception, println}; +use core::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 `libkernel`. /// /// It is linked weakly, so that the integration tests can overload its standard behavior. @@ -34,16 +28,6 @@ fn _panic_exit() -> ! { } } -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -75,9 +59,7 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - - unsafe { exception::asynchronous::local_irq_mask() }; + exception::asynchronous::local_irq_mask(); // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -88,7 +70,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/14_virtual_mem_part2_mmio_remap/src/print.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/print.rs similarity index 85% rename from 14_virtual_mem_part2_mmio_remap/src/print.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/print.rs index 9ec13a28..8e303046 100644 --- a/14_virtual_mem_part2_mmio_remap/src/print.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/15_virtual_mem_part3_precomputed_tables/src/state.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/state.rs similarity index 97% rename from 15_virtual_mem_part3_precomputed_tables/src/state.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/state.rs index 0af3688c..6d99beed 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/state.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/state.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! State information about the kernel itself. diff --git a/13_exceptions_part2_peripheral_IRQs/src/synchronization.rs b/14_virtual_mem_part2_mmio_remap/kernel/src/synchronization.rs similarity index 89% rename from 13_exceptions_part2_peripheral_IRQs/src/synchronization.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/src/synchronization.rs index 4b4c4c3f..5740b63e 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/synchronization.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } /// A reader-writer exclusion type. @@ -38,10 +38,10 @@ pub mod interface { type Data; /// Grants temporary mutable access to the encapsulated data. - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; + 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(&self, f: impl FnOnce(&Self::Data) -> R) -> R; + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; } } @@ -105,7 +105,7 @@ use crate::{exception, state}; impl interface::Mutex for IRQSafeNullLock { 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() }; @@ -118,7 +118,7 @@ impl interface::Mutex for IRQSafeNullLock { impl interface::ReadWriteEx for InitStateLock { type Data = T; - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { + 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" @@ -133,7 +133,7 @@ impl interface::ReadWriteEx for InitStateLock { f(data) } - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { let data = unsafe { &*self.data.get() }; f(data) 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 00000000..a9d50120 --- /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/15_virtual_mem_part3_precomputed_tables/tests/00_console_sanity.rb b/14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rb similarity index 81% rename from 15_virtual_mem_part3_precomputed_tables/tests/00_console_sanity.rb rename to 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rb index 48c9703d..8be7a2f1 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/00_console_sanity.rb +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2019-2022 Andre Richter +# Copyright (c) 2019-2023 Andre Richter -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify sending and receiving works as expected. class TxRxHandshakeTest < SubtestBase @@ -40,9 +40,9 @@ class RxStatisticsTest < SubtestBase 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 00000000..d7409173 --- /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/16_virtual_mem_part4_higher_half_kernel/tests/01_timer_sanity.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs similarity index 67% rename from 16_virtual_mem_part4_higher_half_kernel/tests/01_timer_sanity.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs index 9b2b228d..c0a570e4 100644 --- a/16_virtual_mem_part4_higher_half_kernel/tests/01_timer_sanity.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Timer sanity tests. @@ -11,14 +11,24 @@ #![test_runner(libkernel::test_runner)] use core::time::Duration; -use libkernel::{bsp, cpu, exception, memory, time, time::interface::TimeManager}; +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::console::qemu_bring_up_console(); + bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. @@ -36,6 +46,7 @@ fn timer_is_counting() { /// 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) } diff --git a/14_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs similarity index 69% rename from 14_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs index e146aa3e..3abe91fc 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. @@ -21,8 +21,6 @@ use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { - use libkernel::driver::interface::DriverManager; - exception::handling_init(); // This line will be printed as the test header. @@ -40,21 +38,9 @@ unsafe fn kernel_init() -> ! { info!("Enabling MMU failed: {}", e); cpu::qemu_exit_failure() } - // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); - - // 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. + bsp::driver::qemu_bring_up_console(); info!("Writing beyond mapped area to address 9 GiB..."); let big_addr: u64 = 9 * 1024 * 1024 * 1024; diff --git a/15_virtual_mem_part3_precomputed_tables/tests/03_exception_restore_sanity.rb b/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rb similarity index 65% rename from 15_virtual_mem_part3_precomputed_tables/tests/03_exception_restore_sanity.rb rename to 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rb index c3c725ed..02f51f74 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/03_exception_restore_sanity.rb +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2022 Andre Richter +# Copyright (c) 2022-2023 Andre Richter -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify that exception restore works. class ExceptionRestoreTest < SubtestBase @@ -17,9 +17,9 @@ class ExceptionRestoreTest < SubtestBase end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Test registration -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- def subtest_collection [ExceptionRestoreTest.new] end diff --git a/14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs similarity index 69% rename from 14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs index c6ff7b3d..77ec2d41 100644 --- a/14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter //! A simple sanity test to see if exception restore code works. @@ -30,8 +30,6 @@ fn nested_system_call() { #[no_mangle] unsafe fn kernel_init() -> ! { - use libkernel::driver::interface::DriverManager; - exception::handling_init(); // This line will be printed as the test header. @@ -49,21 +47,9 @@ unsafe fn kernel_init() -> ! { info!("Enabling MMU failed: {}", e); cpu::qemu_exit_failure() } - // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); - - // 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. + bsp::driver::qemu_bring_up_console(); info!("Making a dummy system call"); 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 00000000..ac7c8ae4 --- /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/tests/boot_test_string.rb b/14_virtual_mem_part2_mmio_remap/kernel/tests/boot_test_string.rb similarity index 100% rename from 14_virtual_mem_part2_mmio_remap/tests/boot_test_string.rb rename to 14_virtual_mem_part2_mmio_remap/kernel/tests/boot_test_string.rb diff --git a/13_exceptions_part2_peripheral_IRQs/tests/panic_exit_success/mod.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_exit_success/mod.rs similarity index 77% rename from 13_exceptions_part2_peripheral_IRQs/tests/panic_exit_success/mod.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/tests/panic_exit_success/mod.rs index 908fac51..449ad6f9 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/panic_exit_success/mod.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_exit_success/mod.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter /// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. #[no_mangle] diff --git a/15_virtual_mem_part3_precomputed_tables/tests/panic_wait_forever/mod.rs b/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_wait_forever/mod.rs similarity index 74% rename from 15_virtual_mem_part3_precomputed_tables/tests/panic_wait_forever/mod.rs rename to 14_virtual_mem_part2_mmio_remap/kernel/tests/panic_wait_forever/mod.rs index 7a4effa5..9ac19144 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/panic_wait_forever/mod.rs +++ b/14_virtual_mem_part2_mmio_remap/kernel/tests/panic_wait_forever/mod.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter /// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. #[no_mangle] diff --git a/14_virtual_mem_part2_mmio_remap/test-macros/Cargo.toml b/14_virtual_mem_part2_mmio_remap/libraries/test-macros/Cargo.toml similarity index 100% rename from 14_virtual_mem_part2_mmio_remap/test-macros/Cargo.toml rename to 14_virtual_mem_part2_mmio_remap/libraries/test-macros/Cargo.toml diff --git a/13_exceptions_part2_peripheral_IRQs/test-macros/src/lib.rs b/14_virtual_mem_part2_mmio_remap/libraries/test-macros/src/lib.rs similarity index 85% rename from 13_exceptions_part2_peripheral_IRQs/test-macros/src/lib.rs rename to 14_virtual_mem_part2_mmio_remap/libraries/test-macros/src/lib.rs index 83025a09..52cf893d 100644 --- a/13_exceptions_part2_peripheral_IRQs/test-macros/src/lib.rs +++ b/14_virtual_mem_part2_mmio_remap/libraries/test-macros/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter use proc_macro::TokenStream; use proc_macro2::Span; @@ -11,7 +11,7 @@ use syn::{parse_macro_input, Ident, ItemFn}; 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_name = &format!("{}", f.sig.ident); let test_ident = Ident::new( &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), Span::call_site(), diff --git a/14_virtual_mem_part2_mmio_remap/test-types/Cargo.toml b/14_virtual_mem_part2_mmio_remap/libraries/test-types/Cargo.toml similarity index 100% rename from 14_virtual_mem_part2_mmio_remap/test-types/Cargo.toml rename to 14_virtual_mem_part2_mmio_remap/libraries/test-types/Cargo.toml diff --git a/13_exceptions_part2_peripheral_IRQs/test-types/src/lib.rs b/14_virtual_mem_part2_mmio_remap/libraries/test-types/src/lib.rs similarity index 82% rename from 13_exceptions_part2_peripheral_IRQs/test-types/src/lib.rs rename to 14_virtual_mem_part2_mmio_remap/libraries/test-types/src/lib.rs index 922c2a1c..38961a9c 100644 --- a/13_exceptions_part2_peripheral_IRQs/test-types/src/lib.rs +++ b/14_virtual_mem_part2_mmio_remap/libraries/test-types/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Types for the `custom_test_frameworks` implementation. diff --git a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs b/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs deleted file mode 100644 index c814219c..00000000 --- a/14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } -} - -//-------------------------------------------------------------------------------------------------- -// 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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; - - 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) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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_virtual_mem_part2_mmio_remap/src/bsp/device_driver/common.rs b/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/common.rs deleted file mode 100644 index fd9e988e..00000000 --- a/14_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-2022 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_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs b/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi.rs deleted file mode 100644 index fb9edf88..00000000 --- a/14_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-2022 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/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs b/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs deleted file mode 100644 index c75bf9be..00000000 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console, cpu, driver}; -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 driver::interface::DeviceDriver; - - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START.as_usize()); - let mut panic_uart = - device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.as_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. -#[cfg(feature = "test_build")] -pub fn qemu_bring_up_console() {} diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs b/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index 53168752..00000000 --- a/14_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-2022 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/14_virtual_mem_part2_mmio_remap/src/driver.rs b/14_virtual_mem_part2_mmio_remap/src/driver.rs deleted file mode 100644 index 7b800dbc..00000000 --- a/14_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-2022 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/14_virtual_mem_part2_mmio_remap/src/time.rs b/14_virtual_mem_part2_mmio_remap/src/time.rs deleted file mode 100644 index 6d92b196..00000000 --- a/14_virtual_mem_part2_mmio_remap/src/time.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020-2022 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; - -//-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports -//-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - 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_part3_precomputed_tables/.vscode/settings.json b/15_virtual_mem_part3_precomputed_tables/.vscode/settings.json index 0a8d7c09..9ef30cd0 100644 --- a/15_virtual_mem_part3_precomputed_tables/.vscode/settings.json +++ b/15_virtual_mem_part3_precomputed_tables/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index 29683180..1bef088b 100644 --- a/15_virtual_mem_part3_precomputed_tables/Cargo.lock +++ b/15_virtual_mem_part3_precomputed_tables/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,8 +15,7 @@ dependencies = [ name = "mingo" version = "0.15.0" dependencies = [ - "cortex-a", - "mingo", + "aarch64-cpu", "qemu-exit", "test-macros", "test-types", @@ -25,11 +24,11 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.37" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" dependencies = [ - "unicode-xid", + "unicode-ident", ] [[package]] @@ -40,22 +39,22 @@ checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" [[package]] name = "quote" -version = "1.0.17" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "syn" -version = "1.0.91" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" dependencies = [ "proc-macro2", "quote", - "unicode-xid", + "unicode-ident", ] [[package]] @@ -74,12 +73,12 @@ version = "0.1.0" [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" [[package]] -name = "unicode-xid" -version = "0.2.2" +name = "unicode-ident" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/15_virtual_mem_part3_precomputed_tables/Cargo.toml b/15_virtual_mem_part3_precomputed_tables/Cargo.toml index 1c39f36f..6480a727 100644 --- a/15_virtual_mem_part3_precomputed_tables/Cargo.toml +++ b/15_virtual_mem_part3_precomputed_tables/Cargo.toml @@ -1,67 +1,9 @@ -[package] -name = "mingo" -version = "0.15.0" -authors = ["Andre Richter "] -edition = "2021" +[workspace] + +members = [ + "libraries/*", + "kernel" +] [profile.release] lto = true - -[features] -default = [] -bsp_rpi3 = ["tock-registers"] -bsp_rpi4 = ["tock-registers"] -test_build = ["qemu-exit"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] -test-types = { path = "test-types" } - -# Optional dependencies -tock-registers = { version = "0.7.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] -cortex-a = { version = "7.x.x" } - -##-------------------------------------------------------------------------------------------------- -## Testing -##-------------------------------------------------------------------------------------------------- - -[dev-dependencies] -test-macros = { path = "test-macros" } - -# The following line is a workaround, as suggested in [1], to enable a feature in test-builds only. -# This allows building the library part of the kernel with specialized code for testing. -# -# -# [1] https://github.com/rust-lang/cargo/issues/2911#issuecomment-749580481 -mingo = { path = ".", features = ["test_build"] } - -# 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/Makefile b/15_virtual_mem_part3_precomputed_tables/Makefile index fec9097c..bc23270d 100644 --- a/15_virtual_mem_part3_precomputed_tables/Makefile +++ b/15_virtual_mem_part3_precomputed_tables/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -41,7 +42,7 @@ ifeq ($(BSP),rpi3) 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 + 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 @@ -55,7 +56,7 @@ else ifeq ($(BSP),rpi4) 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 + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif @@ -67,16 +68,19 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -TT_TOOL_PATH = translation_table_tool - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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)) $(LAST_BUILD_CONFIG) +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)/*) @@ -101,11 +105,10 @@ COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -TEST_CMD = cargo test $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary @@ -183,7 +186,7 @@ $(KERNEL_BIN): $(KERNEL_ELF_TTABLES) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -219,6 +222,8 @@ chainboot: $(KERNEL_BIN) ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean @@ -241,7 +246,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -251,12 +255,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- @@ -293,6 +291,8 @@ gdb gdb-opt0: $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- .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: @@ -311,7 +311,11 @@ test_boot: $(KERNEL_BIN) ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER - #!/usr/bin/env bash +#!/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') diff --git a/15_virtual_mem_part3_precomputed_tables/README.md b/15_virtual_mem_part3_precomputed_tables/README.md index 37d157cc..3fdc2385 100644 --- a/15_virtual_mem_part3_precomputed_tables/README.md +++ b/15_virtual_mem_part3_precomputed_tables/README.md @@ -118,7 +118,7 @@ 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 link.ld -o example.elf +$ ld.lld start.o -T kernel.ld -o example.elf ``` ```c-objdump @@ -326,7 +326,7 @@ space: ```console $ clang --target=aarch64-none-elf -Iinclude -Wall -fpic -c start.c -o start.o -$ ld.lld start.o -T link.ld -o example.elf +$ ld.lld start.o -T kernel.ld -o example.elf ``` ```c-objdump @@ -473,7 +473,7 @@ the precompute use-case. The additional `#[no_mangle]` is added because we will 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 `link.ld` linker +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. @@ -540,15 +540,15 @@ already, the only missing piece that's left is the offline computation of the tr ### The Translation Table Tool -The tool for translation table computation is located in the folder `translation_table_tool` in the -root directory. 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: +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 translation_table_tool +$ tree tools/translation_table_tool -translation_table_tool +tools/translation_table_tool ├── arch.rb ├── bsp.rb ├── generic.rb @@ -568,7 +568,7 @@ In the `Makefile`, the tool is invoked after compiling and linking the kernel, a to the kernel's `ELF` file: ```Makefile -TT_TOOL_PATH = translation_table_tool +TT_TOOL_PATH = tools/translation_table_tool KERNEL_ELF_RAW = target/$(TARGET)/release/kernel # [...] @@ -637,7 +637,7 @@ def kernel_map_binary mapping_descriptors.each do |i| print 'Generating'.rjust(12).green.bold print ' ' - puts i.to_s + puts i TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) end @@ -775,30 +775,30 @@ Minipush 1.0 Raspberry Pi 3 [ML] Requesting binary -[MP] ⏩ Pushing 259 KiB ======================================🦀 100% 129 KiB/s Time: 00:00:02 +[MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 [ML] Loaded! Executing the payload now -[ 2.891133] mingo version 0.15.0 -[ 2.891341] Booting on: Raspberry Pi 3 -[ 2.891796] MMU online: -[ 2.892088] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 2.893833] Virtual Physical Size Attr Entity -[ 2.895577] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 2.897322] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack -[ 2.898925] 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.900538] 0x0000_0000_0009_0000..0x0000_0000_000c_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss -[ 2.902109] 0x0000_0000_000d_0000..0x0000_0000_000d_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM GPIO -[ 2.903561] | BCM PL011 UART -[ 2.905078] 0x0000_0000_000e_0000..0x0000_0000_000e_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Peripheral Interrupt Controller -[ 2.906822] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 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/Cargo.toml 15_virtual_mem_part3_precomputed_tables/Cargo.toml ---- 14_virtual_mem_part2_mmio_remap/Cargo.toml -+++ 15_virtual_mem_part3_precomputed_tables/Cargo.toml +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" @@ -808,88 +808,18 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/Cargo.toml 15_virtual_mem_part3_precom edition = "2021" -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 -@@ -69,12 +69,19 @@ - ##-------------------------------------------------------------------------------------------------- - KERNEL_LINKER_SCRIPT = link.ld - -+TT_TOOL_PATH = translation_table_tool -+ - 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_RAW).d)) $(LAST_BUILD_CONFIG) -+KERNEL_ELF_RAW_DEPS = $(filter-out modulo: ,$(file < $(KERNEL_ELF_RAW).d)) $(LAST_BUILD_CONFIG) -+ -+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 +111,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 +162,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") -@@ -300,6 +316,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/src/_arch/aarch64/cpu/boot.rs 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs ---- 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.rs -+++ 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs +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 cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; -@@ -71,9 +72,16 @@ +@@ -75,9 +76,16 @@ /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] @@ -908,10 +838,10 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.rs 15_virtu asm::eret() } -diff -uNr 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.s 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s ---- 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.s -+++ 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s -@@ -56,11 +56,14 @@ +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: @@ -924,15 +854,27 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/cpu/boot.s 15_virtua + 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/src/_arch/aarch64/memory/mmu/translation_table.rs 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu/translation_table.rs ---- 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu/translation_table.rs -+++ 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu/translation_table.rs +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 @@ } @@ -1135,72 +1077,11 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/_arch/aarch64/memory/mmu/translati //-------------------------------------------------------------------------------------------------- -diff -uNr 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/console.rs ---- 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/console.rs -+++ 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/console.rs -@@ -22,6 +22,7 @@ - /// # Safety - /// - /// - Use only for printing during a panic. -+#[cfg(not(feature = "test_build"))] - pub unsafe fn panic_console_out() -> impl fmt::Write { - use driver::interface::DeviceDriver; - -@@ -45,6 +46,23 @@ - panic_uart - } - -+/// Reduced version for test builds. -+#[cfg(feature = "test_build")] -+pub unsafe fn panic_console_out() -> impl fmt::Write { -+ use driver::interface::DeviceDriver; -+ -+ let mut panic_uart = -+ device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.as_usize()); -+ -+ let maybe_uart_mmio_start_addr = super::PL011_UART.virt_mmio_start_addr(); -+ -+ panic_uart -+ .init(maybe_uart_mmio_start_addr) -+ .unwrap_or_else(|_| cpu::qemu_exit_failure()); -+ -+ panic_uart -+} -+ - /// Return a reference to the console. - pub fn console() -> &'static impl console::interface::All { - &super::PL011_UART -@@ -56,7 +74,15 @@ - - /// 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. - #[cfg(feature = "test_build")] --pub fn qemu_bring_up_console() {} -+pub fn qemu_bring_up_console() { -+ use driver::interface::DeviceDriver; -+ -+ // Calling the UART's init ensures that the BSP's instance of the UART does remap the MMIO -+ // addresses. -+ unsafe { -+ super::PL011_UART -+ .init() -+ .unwrap_or_else(|_| cpu::qemu_exit_failure()); -+ } -+} - -diff -uNr 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld ---- 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld -+++ 15_virtual_mem_part3_precomputed_tables/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/src/bsp/raspberrypi/link.ld 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld ---- 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld -+++ 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld +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-2022 Andre Richter + * Copyright (c) 2018-2023 Andre Richter */ +INCLUDE kernel_virt_addr_space_size.ld; @@ -1208,10 +1089,25 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld 15_virtual 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/src/bsp/raspberrypi/memory/mmu.rs 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs ---- 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs -+++ 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs +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::{ @@ -1437,10 +1333,33 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/memory/mmu.rs 15_v + ); } -diff -uNr 14_virtual_mem_part2_mmio_remap/src/main.rs 15_virtual_mem_part3_precomputed_tables/src/main.rs ---- 14_virtual_mem_part2_mmio_remap/src/main.rs -+++ 15_virtual_mem_part3_precomputed_tables/src/main.rs -@@ -15,31 +15,23 @@ +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. /// @@ -1456,8 +1375,6 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/main.rs 15_virtual_mem_part3_preco +/// - Printing will not work until the respective driver's MMIO is remapped. #[no_mangle] unsafe fn kernel_init() -> ! { - use driver::interface::DriverManager; - exception::handling_init(); - - let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { @@ -1468,30 +1385,25 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/main.rs 15_virtual_mem_part3_preco - if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { - panic!("Enabling MMU failed: {}", e); - } -- // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. - - memory::mmu::post_enable_init(); +- 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(); -+ // Add the mapping records for the precomputed entries first, so that they appear on the top of -+ // the list. + bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); + - // Bring up the drivers needed for printing first. - for i in bsp::driver::driver_manager() - .early_print_device_drivers() -@@ -49,7 +41,7 @@ - i.init().unwrap_or_else(|_| cpu::wait_forever()); - } - bsp::driver::driver_manager().post_early_print_device_driver_init(); -- // Printing available again from here on. -+ // Printing available from here on. + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); - // Now bring up the remaining drivers. - for i in bsp::driver::driver_manager() -diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/translation_table.rs ---- 14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs -+++ 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/translation_table.rs +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. @@ -1552,7 +1464,7 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs 15 + let mut tables = MinSizeTranslationTable::new_for_runtime(); - tables.init(); -+ assert!(tables.init().is_ok()); ++ assert_eq!(tables.init(), Ok(())); let virt_start_page_addr: PageAddress = PageAddress::from(0); let virt_end_exclusive_page_addr: PageAddress = @@ -1579,9 +1491,9 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu/translation_table.rs 15 } } -diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs ---- 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs -+++ 15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs +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, @@ -1592,7 +1504,7 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 }; use core::{fmt, num::NonZeroUsize}; -@@ -73,7 +74,7 @@ +@@ -73,17 +74,9 @@ // Private Code //-------------------------------------------------------------------------------------------------- use interface::MMU; @@ -1600,8 +1512,18 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 +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 -@@ -101,13 +102,21 @@ +-/// 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))?; @@ -1626,7 +1548,7 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -@@ -155,27 +164,16 @@ +@@ -155,27 +156,24 @@ } } @@ -1639,6 +1561,14 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 -/// - 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, @@ -1659,15 +1589,15 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 } /// MMIO remapping in the kernel translation tables. -@@ -224,21 +222,24 @@ +@@ -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. /// --/// # Safety --/// -/// - See [`bsp::memory::mmu::kernel_map_binary()`]. -pub unsafe fn kernel_map_binary() -> Result, &'static str> { - let phys_kernel_tables_base_addr = @@ -1675,8 +1605,6 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 - tables.init(); - tables.phys_base_address() - }); -- -- bsp::memory::mmu::kernel_map_binary()?; +/// 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, @@ -1685,7 +1613,7 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 + .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) +} -- Ok(phys_kernel_tables_base_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. @@ -1694,10 +1622,16 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 +) -> 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,6 +247,7 @@ +@@ -246,56 +252,9 @@ /// # Safety /// /// - Crucial function during kernel init. Changes the the complete memory view of the processor. @@ -1705,11 +1639,19 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 pub unsafe fn enable_mmu_and_caching( phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError> { -@@ -261,41 +263,3 @@ - pub fn kernel_print_mappings() { - mapping_record::kernel_print() + 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 -//-------------------------------------------------------------------------------------------------- @@ -1729,7 +1671,7 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 - 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 = alloc::kernel_mmio_va_allocator() +- let virt_region = page_alloc::kernel_mmio_va_allocator() - .lock(|allocator| allocator.alloc(num_pages)) - .unwrap(); - @@ -1748,60 +1690,81 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/src/memory/mmu.rs 15_virtual_mem_part3 - } -} -diff -uNr 14_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rs 15_virtual_mem_part3_precomputed_tables/tests/00_console_sanity.rs ---- 14_virtual_mem_part2_mmio_remap/tests/00_console_sanity.rs -+++ 15_virtual_mem_part3_precomputed_tables/tests/00_console_sanity.rs -@@ -11,7 +11,7 @@ - /// Console tests should time out on the I/O harness in case of panic. - mod panic_wait_forever; +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 @@ + } + } --use libkernel::{bsp, console, cpu, exception, print}; -+use libkernel::{bsp, console, cpu, exception, memory, print}; ++/// Initialize the memory subsystem. ++pub fn init() { ++ mmu::kernel_init_mmio_va_allocator(); ++} ++ + //-------------------------------------------------------------------------------------------------- + // Testing + //-------------------------------------------------------------------------------------------------- - #[no_mangle] - unsafe fn kernel_init() -> ! { -@@ -19,6 +19,7 @@ - use console::interface::*; +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(); -+ memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); +- +- 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/tests/01_timer_sanity.rs 15_virtual_mem_part3_precomputed_tables/tests/01_timer_sanity.rs ---- 14_virtual_mem_part2_mmio_remap/tests/01_timer_sanity.rs -+++ 15_virtual_mem_part3_precomputed_tables/tests/01_timer_sanity.rs -@@ -11,12 +11,13 @@ - #![test_runner(libkernel::test_runner)] - - use core::time::Duration; --use libkernel::{bsp, cpu, exception, time, time::interface::TimeManager}; -+use libkernel::{bsp, cpu, exception, memory, time, time::interface::TimeManager}; - use test_macros::kernel_test; - +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(); -+ memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); +- +- 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/tests/02_exception_sync_page_fault.rs 15_virtual_mem_part3_precomputed_tables/tests/02_exception_sync_page_fault.rs ---- 14_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs -+++ 15_virtual_mem_part3_precomputed_tables/tests/02_exception_sync_page_fault.rs -@@ -21,40 +21,12 @@ - +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() -> ! { -- use libkernel::driver::interface::DriverManager; -- exception::handling_init(); -- -- // This line will be printed as the test header. -- println!("Testing synchronous exception handling by causing a page fault"); -- ++ 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); @@ -1814,41 +1777,27 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/tests/02_exception_sync_page_fault.rs - info!("Enabling MMU failed: {}", e); - cpu::qemu_exit_failure() - } -- // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. - - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); - -- // 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. -+ // This line will be printed as the test header. -+ println!("Testing synchronous exception handling by causing a page fault"); - +- 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/tests/03_exception_restore_sanity.rs 15_virtual_mem_part3_precomputed_tables/tests/03_exception_restore_sanity.rs ---- 14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rs -+++ 15_virtual_mem_part3_precomputed_tables/tests/03_exception_restore_sanity.rs -@@ -30,40 +30,12 @@ - +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() -> ! { -- use libkernel::driver::interface::DriverManager; -- exception::handling_init(); -- -- // This line will be printed as the test header. -- println!("Testing exception restore"); -- ++ 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); @@ -1861,54 +1810,121 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/tests/03_exception_restore_sanity.rs 1 - info!("Enabling MMU failed: {}", e); - cpu::qemu_exit_failure() - } -- // Printing will silently fail from here on, because the driver's MMIO is not remapped yet. - - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); +- memory::mmu::post_enable_init(); +- bsp::driver::qemu_bring_up_console(); +- + info!("Making a dummy system call"); -- // 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()); + // 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); - } -- bsp::driver::driver_manager().post_early_print_device_driver_init(); -- // Printing available again from here on. -+ // This line will be printed as the test header. -+ println!("Testing exception restore"); +- +- memory::mmu::post_enable_init(); ++ memory::init(); + bsp::driver::qemu_bring_up_console(); - info!("Making a dummy system call"); ++ exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + test_main(); -diff -uNr 14_virtual_mem_part2_mmio_remap/tests/04_exception_irq_sanity.rs 15_virtual_mem_part3_precomputed_tables/tests/04_exception_irq_sanity.rs ---- 14_virtual_mem_part2_mmio_remap/tests/04_exception_irq_sanity.rs -+++ 15_virtual_mem_part3_precomputed_tables/tests/04_exception_irq_sanity.rs -@@ -10,11 +10,12 @@ - #![reexport_test_harness_main = "test_main"] - #![test_runner(libkernel::test_runner)] +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 --use libkernel::{bsp, cpu, exception}; -+use libkernel::{bsp, cpu, exception, memory}; - use test_macros::kernel_test; +-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) - #[no_mangle] - unsafe fn kernel_init() -> ! { -+ memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); - exception::handling_init(); -diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/arch.rb 15_virtual_mem_part3_precomputed_tables/translation_table_tool/arch.rb ---- 14_virtual_mem_part2_mmio_remap/translation_table_tool/arch.rb -+++ 15_virtual_mem_part3_precomputed_tables/translation_table_tool/arch.rb +@@ -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-2022 Andre Richter ++# Copyright (c) 2021-2023 Andre Richter + +# Bitfield manipulation. +class BitField @@ -2217,21 +2233,21 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/arch.rb 15_virt +end +end -diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/bsp.rb 15_virtual_mem_part3_precomputed_tables/translation_table_tool/bsp.rb ---- 14_virtual_mem_part2_mmio_remap/translation_table_tool/bsp.rb -+++ 15_virtual_mem_part3_precomputed_tables/translation_table_tool/bsp.rb +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-2022 Andre Richter ++# 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('src/bsp/raspberrypi/memory.rs').split("\n") ++ MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + + def initialize + @kernel_granule = Granule64KiB @@ -2271,15 +2287,15 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/bsp.rb 15_virtu + end +end -diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/generic.rb 15_virtual_mem_part3_precomputed_tables/translation_table_tool/generic.rb ---- 14_virtual_mem_part2_mmio_remap/translation_table_tool/generic.rb -+++ 15_virtual_mem_part3_precomputed_tables/translation_table_tool/generic.rb +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-2022 Andre Richter ++# Copyright (c) 2021-2023 Andre Richter + +module Granule64KiB + SIZE = 64 * 1024 @@ -2428,7 +2444,7 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/generic.rb 15_v + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' -+ puts i.to_s ++ puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end @@ -2455,15 +2471,15 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/generic.rb 15_v + BSP.phys_kernel_tables_base_addr_offset_in_file) +end -diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/kernel_elf.rb 15_virtual_mem_part3_precomputed_tables/translation_table_tool/kernel_elf.rb ---- 14_virtual_mem_part2_mmio_remap/translation_table_tool/kernel_elf.rb -+++ 15_virtual_mem_part3_precomputed_tables/translation_table_tool/kernel_elf.rb +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-2022 Andre Richter ++# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF @@ -2556,16 +2572,16 @@ diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/kernel_elf.rb 1 + end +end -diff -uNr 14_virtual_mem_part2_mmio_remap/translation_table_tool/main.rb 15_virtual_mem_part3_precomputed_tables/translation_table_tool/main.rb ---- 14_virtual_mem_part2_mmio_remap/translation_table_tool/main.rb -+++ 15_virtual_mem_part3_precomputed_tables/translation_table_tool/main.rb +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-2022 Andre Richter ++# Copyright (c) 2021-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' 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 00000000..a0652b4f --- /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/build.rs b/15_virtual_mem_part3_precomputed_tables/kernel/build.rs similarity index 100% rename from 15_virtual_mem_part3_precomputed_tables/build.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/build.rs diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu.rs similarity index 93% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu.rs index 66da661c..2d010473 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs similarity index 92% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs index 0a606a48..b76176df 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -12,12 +12,16 @@ //! crate::cpu::boot::arch_boot use crate::{memory, memory::Address}; +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; -use cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Private Code diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s similarity index 86% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s index dd2b50b8..48c3f8a7 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s @@ -18,9 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _EL2, 0x8 -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -32,12 +29,12 @@ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL - cmp x0, _EL2 + 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, _core_id_mask + 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 @@ -63,6 +60,14 @@ _start: 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 diff --git a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/smp.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/smp.rs similarity index 88% rename from 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/smp.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/smp.rs index 351fde62..49192038 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/smp.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/smp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural symmetric multiprocessing. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::smp::arch_smp -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.rs similarity index 88% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.rs index 495dba34..73019800 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! @@ -11,9 +11,9 @@ //! //! crate::exception::arch_exception -use crate::{bsp, exception}; +use crate::exception; +use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::InMemoryRegister, @@ -46,7 +46,7 @@ struct ExceptionContext { /// Saved program status. spsr_el1: SpsrEL1, - // Exception syndrome register. + /// Exception syndrome register. esr_el1: EsrEL1, } @@ -68,17 +68,17 @@ fn default_exception_handler(exc: &ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { +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] -unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } @@ -87,7 +87,7 @@ unsafe extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { #[cfg(feature = "test_build")] { const TEST_SVC_ID: u64 = 0x1337; @@ -103,15 +103,13 @@ unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { } #[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); +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] -unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -120,17 +118,17 @@ unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } @@ -139,17 +137,17 @@ unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { //------------------------------------------------------------------------------ #[no_mangle] -unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { +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) { +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) { +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception.s b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.s similarity index 97% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception.s rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.s index 5aae30b9..91805ee7 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception.s +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.s @@ -9,6 +9,7 @@ /// 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 @@ -47,6 +48,9 @@ // 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 diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception/asynchronous.rs similarity index 79% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception/asynchronous.rs index 73b82e65..811ef138 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/exception/asynchronous.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! @@ -11,8 +11,8 @@ //! //! crate::exception::asynchronous::arch_asynchronous +use aarch64_cpu::registers::*; use core::arch::asm; -use cortex_a::registers::*; use tock_registers::interfaces::{Readable, Writeable}; //-------------------------------------------------------------------------------------------------- @@ -83,42 +83,32 @@ pub fn is_local_irq_masked() -> bool { /// /// "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) - ); +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. -/// -/// # 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) - ); +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). -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. #[inline(always)] -pub unsafe fn local_irq_mask_save() -> u64 { +pub fn local_irq_mask_save() -> u64 { let saved = DAIF.get(); local_irq_mask(); @@ -127,12 +117,11 @@ pub unsafe fn local_irq_mask_save() -> u64 { /// Restore the interrupt mask bits (DAIF) using the callee's argument. /// -/// # Safety +/// # Invariant /// -/// - Changes the HW state of the executing core. /// - No sanity checks on the input. #[inline(always)] -pub unsafe fn local_irq_restore(saved: u64) { +pub fn local_irq_restore(saved: u64) { DAIF.set(saved); } diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs similarity index 98% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs index e2db2d23..e0717a7f 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! @@ -17,8 +17,8 @@ use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical}, }; +use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu/translation_table.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs similarity index 99% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu/translation_table.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs index 53f59216..8cba4cd7 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu/translation_table.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! 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 00000000..ee1c3ef7 --- /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/13_exceptions_part2_peripheral_IRQs/src/bsp.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp.rs similarity index 81% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp.rs index 824787f6..246973bc 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver.rs similarity index 82% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver.rs index eafaf775..2dfaec8d 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm.rs similarity index 64% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm.rs index e83e24c9..8d1cbfbd 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2.rs similarity index 78% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2.rs index 4c68a692..256de704 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICv2 Driver - ARM Generic Interrupt Controller v2. //! @@ -79,36 +79,36 @@ mod gicc; mod gicd; -use crate::{bsp, cpu, driver, exception, memory, synchronization, synchronization::InitStateLock}; -use core::sync::atomic::{AtomicBool, Ordering}; +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- -type HandlerTable = [Option; GICv2::NUM_IRQS]; +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; /// Representation of the GIC. pub struct GICv2 { - gicd_mmio_descriptor: memory::mmu::MMIODescriptor, - gicc_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, } @@ -119,24 +119,22 @@ pub struct GICv2 { 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; + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; /// Create an instance. /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. + /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new( - gicd_mmio_descriptor: memory::mmu::MMIODescriptor, - gicc_mmio_descriptor: memory::mmu::MMIODescriptor, + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, ) -> Self { Self { - gicd_mmio_descriptor, - gicc_mmio_descriptor, - gicd: gicd::GICD::new(gicd_mmio_descriptor.start_addr().as_usize()), - gicc: gicc::GICC::new(gicc_mmio_descriptor.start_addr().as_usize()), - is_mmio_remapped: AtomicBool::new(false), - handler_table: InitStateLock::new([None; Self::NUM_IRQS]), + 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]), } } } @@ -147,25 +145,13 @@ impl GICv2 { use synchronization::interface::ReadWriteEx; impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "GICv2 (ARM Generic Interrupt Controller v2)" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { - let remapped = self.is_mmio_remapped.load(Ordering::Relaxed); - if !remapped { - // GICD - let mut virt_addr = memory::mmu::kernel_map_mmio("GICD", &self.gicd_mmio_descriptor)?; - self.gicd.set_mmio(virt_addr.as_usize()); - - // GICC - virt_addr = memory::mmu::kernel_map_mmio("GICC", &self.gicc_mmio_descriptor)?; - self.gicc.set_mmio(virt_addr.as_usize()); - - // Conclude remapping. - self.is_mmio_remapped.store(true, Ordering::Relaxed); - } - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { self.gicd.boot_core_init(); } @@ -182,23 +168,22 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { - let irq_number = irq_number.get(); + let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } - table[irq_number] = Some(descriptor); + table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } - fn enable(&self, irq_number: Self::IRQNumberType) { + fn enable(&self, irq_number: &Self::IRQNumberType) { self.gicd.enable(irq_number); } @@ -221,7 +206,7 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { 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"); + descriptor.handler().handle().expect("Error handling IRQ"); } } }); @@ -238,7 +223,7 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { 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); + info!(" {: >3}. {}", i + 32, handler.name()); } } }); diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs similarity index 79% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs index 1a151d24..0fd16bb3 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicc.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -1,11 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICC Driver - GIC CPU interface. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, exception, synchronization::InitStateLock, + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, }; use tock_registers::{ interfaces::{Readable, Writeable}, @@ -62,13 +64,12 @@ type Registers = MMIODerefWrapper; /// Representation of the GIC CPU interface. pub struct GICC { - registers: InitStateLock, + registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -use crate::synchronization::interface::ReadWriteEx; impl GICC { /// Create an instance. @@ -76,17 +77,12 @@ impl GICC { /// # 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: InitStateLock::new(Registers::new(mmio_start_addr)), + registers: 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: @@ -99,9 +95,7 @@ impl GICC { /// - 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. - }); + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. } /// Enable the interface - start accepting IRQs. @@ -111,9 +105,7 @@ impl GICC { /// - 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); - }); + self.registers.CTLR.write(CTLR::Enable::SET); } /// Extract the number of the highest-priority pending IRQ. @@ -129,8 +121,7 @@ impl GICC { &self, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) -> usize { - self.registers - .read(|regs| regs.IAR.read(IAR::InterruptID) as usize) + self.registers.IAR.read(IAR::InterruptID) as usize } /// Complete handling of the currently active IRQ. @@ -149,8 +140,6 @@ impl GICC { irq_number: u32, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) { - self.registers.read(|regs| { - regs.EOIR.write(EOIR::EOIINTID.val(irq_number)); - }); + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); } } diff --git a/16_virtual_mem_part4_higher_half_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 similarity index 85% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/arm/gicv2/gicd.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs index 60bbc468..1fc9d70e 100644 --- a/16_virtual_mem_part4_higher_half_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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICD Driver - GIC Distributor. //! @@ -9,8 +9,9 @@ use crate::{ bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, state, synchronization, - synchronization::{IRQSafeNullLock, InitStateLock}, + synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{Readable, Writeable}, @@ -51,9 +52,9 @@ register_structs! { (0x004 => TYPER: ReadOnly), (0x008 => _reserved1), (0x104 => ISENABLER: [ReadWrite; 31]), - (0x108 => _reserved2), + (0x180 => _reserved2), (0x820 => ITARGETSR: [ReadWrite; 248]), - (0x824 => @END), + (0xC00 => @END), } } @@ -64,7 +65,7 @@ register_structs! { (0x100 => ISENABLER: ReadWrite), (0x104 => _reserved2), (0x800 => ITARGETSR: [ReadOnly; 8]), - (0x804 => @END), + (0x820 => @END), } } @@ -84,7 +85,7 @@ pub struct GICD { shared_registers: IRQSafeNullLock, /// Access to banked registers is unguarded. - banked_registers: InitStateLock, + banked_registers: BankedRegisters, } //-------------------------------------------------------------------------------------------------- @@ -121,7 +122,6 @@ impl SharedRegisters { //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -use crate::synchronization::interface::ReadWriteEx; use synchronization::interface::Mutex; impl GICD { @@ -130,20 +130,13 @@ impl GICD { /// # 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: InitStateLock::new(BankedRegisters::new(mmio_start_addr)), + banked_registers: 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: @@ -151,8 +144,7 @@ impl GICD { /// "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)) + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) } /// Route all SPIs to the boot core and enable the distributor. @@ -180,7 +172,7 @@ impl GICD { } /// Enable an interrupt. - pub fn enable(&self, irq_num: super::IRQNumber) { + 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 @@ -191,10 +183,10 @@ impl GICD { // 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; + 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; diff --git a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/bcm.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm.rs similarity index 83% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/bcm.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm.rs index 5a7cc23b..7b7c288b 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/bcm.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs similarity index 76% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs index eea07b75..812156f4 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -1,14 +1,17 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, memory, synchronization, + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, synchronization::IRQSafeNullLock, }; -use core::sync::atomic::{AtomicUsize, Ordering}; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, @@ -109,26 +112,21 @@ 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 { - mmio_descriptor: memory::mmu::MMIODescriptor, - virt_mmio_start_addr: AtomicUsize, inner: IRQSafeNullLock, } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -137,29 +135,16 @@ impl GPIOInner { /// # 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), } } - /// 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 crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. @@ -205,17 +190,21 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new(mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { - mmio_descriptor, - virt_mmio_start_addr: AtomicUsize::new(0), - inner: IRQSafeNullLock::new(GPIOInner::new(mmio_descriptor.start_addr().as_usize())), + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), } } @@ -231,29 +220,9 @@ impl GPIO { 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.mmio_descriptor)?; + type IRQNumberType = IRQNumber; - self.inner - .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; - - self.virt_mmio_start_addr - .store(virt_addr.as_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) + fn compatible(&self) -> &'static str { + Self::COMPATIBLE } } diff --git a/15_virtual_mem_part3_precomputed_tables/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 similarity index 62% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs index 99961fac..62f07800 100644 --- a/15_virtual_mem_part3_precomputed_tables/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 @@ -1,12 +1,18 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Interrupt Controller Driver. mod peripheral_ic; -use crate::{driver, exception, memory}; +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -21,13 +27,12 @@ struct PendingIRQs { // Public Definitions //-------------------------------------------------------------------------------------------------- -pub type LocalIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -pub type PeripheralIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; +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), @@ -52,16 +57,13 @@ impl Iterator for PendingIRQs { type Item = usize; fn next(&mut self) -> Option { - use core::intrinsics::cttz; - - let next = cttz(self.bitmask); - if next == 64 { + if self.bitmask == 0 { return None; } - self.bitmask &= !(1 << next); - - Some(next as usize) + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) } } @@ -69,22 +71,30 @@ impl Iterator for PendingIRQs { // 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 { - const MAX_LOCAL_IRQ_NUMBER: usize = 11; + // 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; - const NUM_PERIPHERAL_IRQS: usize = Self::MAX_PERIPHERAL_IRQ_NUMBER + 1; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; /// Create an instance. /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new( - _local_mmio_descriptor: memory::mmu::MMIODescriptor, - periph_mmio_descriptor: memory::mmu::MMIODescriptor, - ) -> Self { + /// - 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_descriptor), + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), } } } @@ -94,12 +104,10 @@ impl InterruptController { //------------------------------------------------------------------------------ impl driver::interface::DeviceDriver for InterruptController { - fn compatible(&self) -> &'static str { - "BCM Interrupt Controller" - } + type IRQNumberType = IRQNumber; - unsafe fn init(&self) -> Result<(), &'static str> { - self.periph.init() + fn compatible(&self) -> &'static str { + Self::COMPATIBLE } } @@ -108,16 +116,23 @@ impl exception::asynchronous::interface::IRQManager for InterruptController { fn register_handler( &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { - match irq { + match irq_handler_descriptor.number() { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), - IRQNumber::Peripheral(pirq) => self.periph.register_handler(pirq, 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) { + fn enable(&self, irq: &Self::IRQNumberType) { match irq { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), 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 00000000..a26bff8d --- /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 00000000..b424d4be --- /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 00000000..3ce1d8d8 --- /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 00000000..30421dfa --- /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/12_integrated_testing/src/bsp/raspberrypi/cpu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/cpu.rs similarity index 87% rename from 12_integrated_testing/src/bsp/raspberrypi/cpu.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/cpu.rs index 85fb89e4..65cf5abb 100644 --- a/12_integrated_testing/src/bsp/raspberrypi/cpu.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. 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 00000000..a1f55b17 --- /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/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/exception.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception.rs similarity index 67% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/exception.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception.rs index aa6c5a63..a9eaa6ac 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/exception.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/exception/asynchronous.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception/asynchronous.rs similarity index 56% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/exception/asynchronous.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception/asynchronous.rs index dc5ab421..776182fd 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/exception/asynchronous.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -1,15 +1,18 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! BSP asynchronous exception handling. -use crate::{bsp, exception}; +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}; @@ -23,14 +26,3 @@ pub(in crate::bsp) mod irq_map { 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_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld similarity index 87% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld index c4a0b6a4..63393bae 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/raspberrypi/link.ld +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld @@ -3,6 +3,8 @@ * Copyright (c) 2018-2022 Andre Richter */ +INCLUDE kernel_virt_addr_space_size.ld; + PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; @@ -60,7 +62,6 @@ SECTIONS } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; @@ -90,5 +91,13 @@ SECTIONS . += 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 + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } } diff --git a/15_virtual_mem_part3_precomputed_tables/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 similarity index 100% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs similarity index 97% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs index 660409bb..0d963aa3 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! @@ -107,9 +107,6 @@ pub(super) mod map { 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 --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs similarity index 99% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs index f78b57d1..ce3d6750 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. diff --git a/14_virtual_mem_part2_mmio_remap/src/common.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/common.rs similarity index 54% rename from 14_virtual_mem_part2_mmio_remap/src/common.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/common.rs index 678f4a6c..2ad7e4c1 100644 --- a/14_virtual_mem_part2_mmio_remap/src/common.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! General purpose code. @@ -27,3 +27,20 @@ pub const fn align_up(value: usize, alignment: usize) -> usize { (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/13_exceptions_part2_peripheral_IRQs/src/console.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/console.rs similarity index 52% rename from 13_exceptions_part2_peripheral_IRQs/src/console.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/console.rs index e49e241f..f0363464 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/console.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/console.rs @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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: 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 00000000..e92a022b --- /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/14_virtual_mem_part2_mmio_remap/src/cpu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu.rs similarity index 89% rename from 14_virtual_mem_part2_mmio_remap/src/cpu.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/cpu.rs index e1493d1d..8716a918 100644 --- a/14_virtual_mem_part2_mmio_remap/src/cpu.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/15_virtual_mem_part3_precomputed_tables/src/cpu/boot.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/boot.rs similarity index 71% rename from 15_virtual_mem_part3_precomputed_tables/src/cpu/boot.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/cpu/boot.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/13_exceptions_part2_peripheral_IRQs/src/cpu/smp.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/smp.rs similarity index 87% rename from 13_exceptions_part2_peripheral_IRQs/src/cpu/smp.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/smp.rs index 57386f79..de612d58 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/cpu/smp.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/smp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Symmetric multiprocessing. 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 00000000..2edf8b85 --- /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/13_exceptions_part2_peripheral_IRQs/src/exception.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception.rs similarity index 94% rename from 13_exceptions_part2_peripheral_IRQs/src/exception.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/exception.rs index f4af8144..3d5f219f 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/exception.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. @@ -21,7 +21,7 @@ pub use arch_exception::{current_privilege_level, handling_init}; /// Kernel privilege levels. #[allow(missing_docs)] -#[derive(PartialEq)] +#[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, diff --git a/15_virtual_mem_part3_precomputed_tables/src/exception/asynchronous.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous.rs similarity index 63% rename from 15_virtual_mem_part3_precomputed_tables/src/exception/asynchronous.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous.rs index fb1785c2..2c874dd6 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/exception/asynchronous.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous.rs @@ -1,14 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// 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 core::{fmt, marker::PhantomData}; +use crate::{bsp, synchronization}; +use core::marker::PhantomData; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports @@ -22,14 +24,23 @@ pub use arch_asynchronous::{ // Public Definitions //-------------------------------------------------------------------------------------------------- +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + /// Interrupt descriptor. #[derive(Copy, Clone)] -pub struct IRQDescriptor { +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + /// Descriptive name. - pub name: &'static str, + name: &'static str, /// Reference to handler trait object. - pub handler: &'static (dyn interface::IRQHandler + Sync), + handler: &'static (dyn interface::IRQHandler + Sync), } /// IRQContext token. @@ -59,17 +70,16 @@ pub mod interface { /// platform's interrupt controller. pub trait IRQManager { /// The IRQ number type depends on the implementation. - type IRQNumberType; + type IRQNumberType: Copy; /// Register a handler. fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: super::IRQDescriptor, + irq_handler_descriptor: super::IRQHandlerDescriptor, ) -> Result<(), &'static str>; /// Enable an interrupt in the controller. - fn enable(&self, irq_number: Self::IRQNumberType); + fn enable(&self, irq_number: &Self::IRQNumberType); /// Handle pending interrupts. /// @@ -85,17 +95,55 @@ pub mod interface { ); /// Print list of registered handlers. - fn print_handler(&self); + fn print_handler(&self) {} } } -/// A wrapper type for IRQ numbers with integrated range sanity check. -#[derive(Copy, Clone)] -pub struct IRQNumber(usize); +//-------------------------------------------------------------------------------------------------- +// 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. @@ -114,39 +162,29 @@ impl<'irq_context> IRQContext<'irq_context> { } } -impl IRQNumber<{ 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 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); - } + 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 00000000..38919ffe --- /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/13_exceptions_part2_peripheral_IRQs/src/lib.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs similarity index 93% rename from 13_exceptions_part2_peripheral_IRQs/src/lib.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs index 6133f01a..71350bd0 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/lib.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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` library. //! @@ -109,11 +111,18 @@ #![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)] @@ -125,6 +134,7 @@ mod panic_wait; mod synchronization; pub mod bsp; +pub mod common; pub mod console; pub mod cpu; pub mod driver; @@ -177,7 +187,8 @@ pub fn test_runner(tests: &[&test_types::UnitTest]) { #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); test_main(); 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 00000000..e41cfaa0 --- /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/14_virtual_mem_part2_mmio_remap/src/memory.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs similarity index 90% rename from 14_virtual_mem_part2_mmio_remap/src/memory.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs index b5aa666d..6131bdb6 100644 --- a/14_virtual_mem_part2_mmio_remap/src/memory.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management. @@ -18,18 +18,18 @@ use core::{ //-------------------------------------------------------------------------------------------------- /// Metadata trait for marking the type of an address. -pub trait AddressType: Copy + Clone + PartialOrd + PartialEq {} +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} /// Zero-sized type to mark a physical address. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[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)] +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub enum Virtual {} /// Generic address type. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub struct Address { value: usize, _address_type: PhantomData ATYPE>, @@ -136,6 +136,11 @@ impl fmt::Display for Address { } } +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); +} + //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- @@ -160,7 +165,7 @@ mod tests { bsp::memory::mmu::KernelGranule::SIZE * 2 ); - assert_eq!(addr.is_page_aligned(), false); + assert!(!addr.is_page_aligned()); assert_eq!(addr.offset_into_page(), 100); } diff --git a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs similarity index 95% rename from 15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs index 23dc7094..f19758c1 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. @@ -8,8 +8,8 @@ #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; -mod alloc; mod mapping_record; +mod page_alloc; mod translation_table; mod types; @@ -77,14 +77,6 @@ use interface::MMU; 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(); - - alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.initialize(region)); -} - /// Map a region in the kernel's translation tables. /// /// No input checks done, input is passed through to the architectural implementation. @@ -164,6 +156,14 @@ impl AddressSpace { } } +/// 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, @@ -203,7 +203,7 @@ pub unsafe fn kernel_map_mmio( }; let virt_region = - alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; kernel_map_at_unchecked( name, @@ -242,6 +242,11 @@ pub fn try_kernel_page_attributes( .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 @@ -253,13 +258,3 @@ pub unsafe fn enable_mmu_and_caching( ) -> 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() -} diff --git a/14_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/mapping_record.rs similarity index 90% rename from 14_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/mapping_record.rs index d171c6e6..0e079220 100644 --- a/14_virtual_mem_part2_mmio_remap/src/memory/mmu/mapping_record.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/mapping_record.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! A record of mapped pages. @@ -8,7 +8,7 @@ use super::{ AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, Physical, Virtual, }; -use crate::{bsp, info, synchronization, synchronization::InitStateLock, warn}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -76,6 +76,19 @@ impl MappingRecord { 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); @@ -90,8 +103,7 @@ impl MappingRecord { ) -> Option<&mut MappingRecordEntry> { self.inner .iter_mut() - .filter(|x| x.is_some()) - .map(|x| x.as_mut().unwrap()) + .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() { @@ -121,13 +133,13 @@ impl MappingRecord { phys_region, attr, )); + + self.sort(); + Ok(()) } pub fn print(&self) { - const KIB_RSHIFT: u32 = 10; // log2(1024). - const MIB_RSHIFT: u32 = 20; // log2(1024 * 1024). - info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); info!( " {:^44} {:^30} {:^7} {:^9} {:^35}", @@ -142,13 +154,7 @@ impl MappingRecord { let phys_start = i.phys_start_addr; let phys_end_inclusive = phys_start + (size - 1); - 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 (size, unit) = common::size_human_readable_ceil(size); let attr = match i.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", @@ -167,8 +173,7 @@ impl MappingRecord { }; info!( - " {}..{} --> {}..{} | \ - {: >3} {} | {: <3} {} {: <2} | {}", + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", virt_start, virt_end_inclusive, phys_start, diff --git a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu/alloc.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/page_alloc.rs similarity index 93% rename from 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/alloc.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/page_alloc.rs index aadb72ef..344afd20 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu/alloc.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/page_alloc.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter -//! Allocation. +//! Page allocation. use super::MemoryRegion; use crate::{ @@ -44,7 +44,7 @@ impl PageAllocator { } /// Initialize the allocator. - pub fn initialize(&mut self, pool: MemoryRegion) { + pub fn init(&mut self, pool: MemoryRegion) { if self.pool.is_some() { warn!("Already initialized"); return; diff --git a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu/translation_table.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs similarity index 98% rename from 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/translation_table.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs index 5a34a1e6..41368dae 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu/translation_table.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Translation table. @@ -97,7 +97,7 @@ mod tests { // This will occupy a lot of space on the stack. let mut tables = MinSizeTranslationTable::new_for_runtime(); - assert!(tables.init().is_ok()); + assert_eq!(tables.init(), Ok(())); let virt_start_page_addr: PageAddress = PageAddress::from(0); let virt_end_exclusive_page_addr: PageAddress = diff --git a/14_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs similarity index 95% rename from 14_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs index 82d5009c..8feee064 100644 --- a/14_virtual_mem_part2_mmio_remap/src/memory/mmu/types.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit types. @@ -15,13 +15,13 @@ use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; //-------------------------------------------------------------------------------------------------- /// A wrapper type around [Address] that ensures page alignment. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[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, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct MemoryRegion { start: PageAddress, end_exclusive: PageAddress, @@ -29,7 +29,7 @@ pub struct MemoryRegion { /// Architecture agnostic memory attributes. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum MemAttributes { CacheableDRAM, Device, @@ -37,7 +37,7 @@ pub enum MemAttributes { /// Architecture agnostic access permissions. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum AccessPermissions { ReadOnly, ReadWrite, @@ -45,7 +45,7 @@ pub enum AccessPermissions { /// Collection of memory attributes. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, @@ -363,13 +363,11 @@ mod tests { assert_eq!(allocation.num_pages(), 2); assert_eq!(three_region.num_pages(), 1); - let mut count = 0; - for i in allocation.into_iter() { + for (i, alloc) in allocation.into_iter().enumerate() { assert_eq!( - i.into_inner().as_usize(), - count * bsp::memory::mmu::KernelGranule::SIZE + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE ); - count = count + 1; } } } diff --git a/15_virtual_mem_part3_precomputed_tables/src/panic_wait.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/panic_wait.rs similarity index 78% rename from 15_virtual_mem_part3_precomputed_tables/src/panic_wait.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/panic_wait.rs index 08d7d453..c6f3a9c7 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/panic_wait.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/panic_wait.rs @@ -1,22 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. -use crate::{bsp, cpu, exception}; -use core::{fmt, panic::PanicInfo}; +use crate::{cpu, exception, println}; +use core::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 `libkernel`. /// /// It is linked weakly, so that the integration tests can overload its standard behavior. @@ -34,16 +28,6 @@ fn _panic_exit() -> ! { } } -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -75,9 +59,7 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - - unsafe { exception::asynchronous::local_irq_mask() }; + exception::asynchronous::local_irq_mask(); // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -88,7 +70,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/12_integrated_testing/src/print.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/print.rs similarity index 85% rename from 12_integrated_testing/src/print.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/print.rs index 9ec13a28..8e303046 100644 --- a/12_integrated_testing/src/print.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/print.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/13_exceptions_part2_peripheral_IRQs/src/state.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/state.rs similarity index 97% rename from 13_exceptions_part2_peripheral_IRQs/src/state.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/state.rs index 0af3688c..6d99beed 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/state.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/state.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! State information about the kernel itself. diff --git a/16_virtual_mem_part4_higher_half_kernel/src/synchronization.rs b/15_virtual_mem_part3_precomputed_tables/kernel/src/synchronization.rs similarity index 89% rename from 16_virtual_mem_part4_higher_half_kernel/src/synchronization.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/src/synchronization.rs index 4b4c4c3f..5740b63e 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/synchronization.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } /// A reader-writer exclusion type. @@ -38,10 +38,10 @@ pub mod interface { type Data; /// Grants temporary mutable access to the encapsulated data. - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; + 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(&self, f: impl FnOnce(&Self::Data) -> R) -> R; + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; } } @@ -105,7 +105,7 @@ use crate::{exception, state}; impl interface::Mutex for IRQSafeNullLock { 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() }; @@ -118,7 +118,7 @@ impl interface::Mutex for IRQSafeNullLock { impl interface::ReadWriteEx for InitStateLock { type Data = T; - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { + 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" @@ -133,7 +133,7 @@ impl interface::ReadWriteEx for InitStateLock { f(data) } - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { let data = unsafe { &*self.data.get() }; f(data) 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 00000000..a9d50120 --- /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/13_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rb b/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rb similarity index 81% rename from 13_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rb rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rb index 48c9703d..8be7a2f1 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/00_console_sanity.rb +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2019-2022 Andre Richter +# Copyright (c) 2019-2023 Andre Richter -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify sending and receiving works as expected. class TxRxHandshakeTest < SubtestBase @@ -40,9 +40,9 @@ class RxStatisticsTest < SubtestBase end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Test registration -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- def subtest_collection [TxRxHandshakeTest.new, TxStatisticsTest.new, RxStatisticsTest.new] end diff --git a/16_virtual_mem_part4_higher_half_kernel/tests/00_console_sanity.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs similarity index 79% rename from 16_virtual_mem_part4_higher_half_kernel/tests/00_console_sanity.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs index 6595aac1..682ea9b8 100644 --- a/16_virtual_mem_part4_higher_half_kernel/tests/00_console_sanity.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Console sanity tests - RX, TX and statistics. @@ -15,12 +15,11 @@ use libkernel::{bsp, console, cpu, exception, memory, print}; #[no_mangle] unsafe fn kernel_init() -> ! { - use bsp::console::console; - use console::interface::*; + use console::console; exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); diff --git a/12_integrated_testing/tests/01_timer_sanity.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs similarity index 81% rename from 12_integrated_testing/tests/01_timer_sanity.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs index 59ef4a7f..1581a02e 100644 --- a/12_integrated_testing/tests/01_timer_sanity.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Timer sanity tests. @@ -11,13 +11,14 @@ #![test_runner(libkernel::test_runner)] use core::time::Duration; -use libkernel::{bsp, cpu, exception, time, time::interface::TimeManager}; +use libkernel::{bsp, cpu, exception, memory, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - bsp::console::qemu_bring_up_console(); + 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. @@ -35,6 +36,7 @@ fn timer_is_counting() { /// 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) } diff --git a/15_virtual_mem_part3_precomputed_tables/tests/02_exception_sync_page_fault.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs similarity index 88% rename from 15_virtual_mem_part3_precomputed_tables/tests/02_exception_sync_page_fault.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs index 2d4b0977..da64739c 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/02_exception_sync_page_fault.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. @@ -22,8 +22,8 @@ use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + 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"); diff --git a/13_exceptions_part2_peripheral_IRQs/tests/03_exception_restore_sanity.rb b/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rb similarity index 65% rename from 13_exceptions_part2_peripheral_IRQs/tests/03_exception_restore_sanity.rb rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rb index c3c725ed..02f51f74 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/03_exception_restore_sanity.rb +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rb @@ -2,9 +2,9 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2022 Andre Richter +# Copyright (c) 2022-2023 Andre Richter -require_relative '../../common/tests/console_io_test' +require 'console_io_test' # Verify that exception restore works. class ExceptionRestoreTest < SubtestBase @@ -17,9 +17,9 @@ class ExceptionRestoreTest < SubtestBase end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Test registration -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- def subtest_collection [ExceptionRestoreTest.new] end diff --git a/16_virtual_mem_part4_higher_half_kernel/tests/03_exception_restore_sanity.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs similarity index 88% rename from 16_virtual_mem_part4_higher_half_kernel/tests/03_exception_restore_sanity.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs index 983d488f..1a302911 100644 --- a/16_virtual_mem_part4_higher_half_kernel/tests/03_exception_restore_sanity.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter //! A simple sanity test to see if exception restore code works. @@ -31,8 +31,8 @@ fn nested_system_call() { #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); diff --git a/15_virtual_mem_part3_precomputed_tables/tests/04_exception_irq_sanity.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs similarity index 69% rename from 15_virtual_mem_part3_precomputed_tables/tests/04_exception_irq_sanity.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs index 9030424d..fcace897 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/04_exception_irq_sanity.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! IRQ handling sanity tests. @@ -15,8 +15,8 @@ use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); exception::handling_init(); exception::asynchronous::local_irq_unmask(); @@ -32,21 +32,21 @@ fn local_irq_mask_works() { // Precondition: IRQs are unmasked. assert!(exception::asynchronous::is_local_irq_masked()); - unsafe { exception::asynchronous::local_irq_mask() }; + exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); // Restore earlier state. - unsafe { exception::asynchronous::local_irq_unmask() }; + 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() }; + exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); - unsafe { exception::asynchronous::local_irq_unmask() }; + exception::asynchronous::local_irq_unmask(); assert!(exception::asynchronous::is_local_irq_masked()); } @@ -56,12 +56,12 @@ 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() }; + let first = exception::asynchronous::local_irq_mask_save(); assert!(!exception::asynchronous::is_local_irq_masked()); - let second = unsafe { exception::asynchronous::local_irq_mask_save() }; + let second = exception::asynchronous::local_irq_mask_save(); assert_ne!(first, second); - unsafe { exception::asynchronous::local_irq_restore(first) }; + exception::asynchronous::local_irq_restore(first); assert!(exception::asynchronous::is_local_irq_masked()); } diff --git a/15_virtual_mem_part3_precomputed_tables/tests/boot_test_string.rb b/15_virtual_mem_part3_precomputed_tables/kernel/tests/boot_test_string.rb similarity index 100% rename from 15_virtual_mem_part3_precomputed_tables/tests/boot_test_string.rb rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/boot_test_string.rb diff --git a/15_virtual_mem_part3_precomputed_tables/tests/panic_exit_success/mod.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_exit_success/mod.rs similarity index 77% rename from 15_virtual_mem_part3_precomputed_tables/tests/panic_exit_success/mod.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_exit_success/mod.rs index 908fac51..449ad6f9 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/panic_exit_success/mod.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_exit_success/mod.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter /// Overwrites libkernel's `panic_wait::_panic_exit()` with the QEMU-exit version. #[no_mangle] diff --git a/13_exceptions_part2_peripheral_IRQs/tests/panic_wait_forever/mod.rs b/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_wait_forever/mod.rs similarity index 74% rename from 13_exceptions_part2_peripheral_IRQs/tests/panic_wait_forever/mod.rs rename to 15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_wait_forever/mod.rs index 7a4effa5..9ac19144 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/panic_wait_forever/mod.rs +++ b/15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_wait_forever/mod.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter /// Overwrites libkernel's `panic_wait::_panic_exit()` with wait_forever. #[no_mangle] diff --git a/15_virtual_mem_part3_precomputed_tables/test-macros/Cargo.toml b/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/Cargo.toml similarity index 100% rename from 15_virtual_mem_part3_precomputed_tables/test-macros/Cargo.toml rename to 15_virtual_mem_part3_precomputed_tables/libraries/test-macros/Cargo.toml diff --git a/15_virtual_mem_part3_precomputed_tables/test-macros/src/lib.rs b/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/src/lib.rs similarity index 85% rename from 15_virtual_mem_part3_precomputed_tables/test-macros/src/lib.rs rename to 15_virtual_mem_part3_precomputed_tables/libraries/test-macros/src/lib.rs index 83025a09..52cf893d 100644 --- a/15_virtual_mem_part3_precomputed_tables/test-macros/src/lib.rs +++ b/15_virtual_mem_part3_precomputed_tables/libraries/test-macros/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter use proc_macro::TokenStream; use proc_macro2::Span; @@ -11,7 +11,7 @@ use syn::{parse_macro_input, Ident, ItemFn}; 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_name = &format!("{}", f.sig.ident); let test_ident = Ident::new( &format!("{}_TEST_CONTAINER", f.sig.ident.to_string().to_uppercase()), Span::call_site(), diff --git a/15_virtual_mem_part3_precomputed_tables/test-types/Cargo.toml b/15_virtual_mem_part3_precomputed_tables/libraries/test-types/Cargo.toml similarity index 100% rename from 15_virtual_mem_part3_precomputed_tables/test-types/Cargo.toml rename to 15_virtual_mem_part3_precomputed_tables/libraries/test-types/Cargo.toml diff --git a/12_integrated_testing/test-types/src/lib.rs b/15_virtual_mem_part3_precomputed_tables/libraries/test-types/src/lib.rs similarity index 82% rename from 12_integrated_testing/test-types/src/lib.rs rename to 15_virtual_mem_part3_precomputed_tables/libraries/test-types/src/lib.rs index 922c2a1c..38961a9c 100644 --- a/12_integrated_testing/test-types/src/lib.rs +++ b/15_virtual_mem_part3_precomputed_tables/libraries/test-types/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Types for the `custom_test_frameworks` implementation. diff --git a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/time.rs b/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/time.rs deleted file mode 100644 index c814219c..00000000 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } -} - -//-------------------------------------------------------------------------------------------------- -// 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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; - - 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) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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_part3_precomputed_tables/src/bsp/raspberrypi.rs b/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi.rs deleted file mode 100644 index fb9edf88..00000000 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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_part3_precomputed_tables/src/bsp/raspberrypi/console.rs b/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/console.rs deleted file mode 100644 index edb1a831..00000000 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 Andre Richter - -//! BSP console facilities. - -use super::memory; -use crate::{bsp::device_driver, console, cpu, driver}; -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. -#[cfg(not(feature = "test_build"))] -pub unsafe fn panic_console_out() -> impl fmt::Write { - use driver::interface::DeviceDriver; - - let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START.as_usize()); - let mut panic_uart = - device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.as_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 -} - -/// Reduced version for test builds. -#[cfg(feature = "test_build")] -pub unsafe fn panic_console_out() -> impl fmt::Write { - use driver::interface::DeviceDriver; - - let mut panic_uart = - device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.as_usize()); - - let maybe_uart_mmio_start_addr = super::PL011_UART.virt_mmio_start_addr(); - - panic_uart - .init(maybe_uart_mmio_start_addr) - .unwrap_or_else(|_| cpu::qemu_exit_failure()); - - 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. -#[cfg(feature = "test_build")] -pub fn qemu_bring_up_console() { - use driver::interface::DeviceDriver; - - // Calling the UART's init ensures that the BSP's instance of the UART does remap the MMIO - // addresses. - unsafe { - super::PL011_UART - .init() - .unwrap_or_else(|_| cpu::qemu_exit_failure()); - } -} diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/driver.rs b/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index 53168752..00000000 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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_part3_precomputed_tables/src/driver.rs b/15_virtual_mem_part3_precomputed_tables/src/driver.rs deleted file mode 100644 index 7b800dbc..00000000 --- a/15_virtual_mem_part3_precomputed_tables/src/driver.rs +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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_part3_precomputed_tables/src/main.rs b/15_virtual_mem_part3_precomputed_tables/src/main.rs deleted file mode 100644 index 8bc80885..00000000 --- a/15_virtual_mem_part3_precomputed_tables/src/main.rs +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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. -/// -/// 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() -> ! { - use driver::interface::DriverManager; - - exception::handling_init(); - memory::mmu::post_enable_init(); - - // Add the mapping records for the precomputed entries first, so that they appear on the top of - // the list. - bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); - - // 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 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!("{}", 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:"); - 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_part3_precomputed_tables/src/time.rs b/15_virtual_mem_part3_precomputed_tables/src/time.rs deleted file mode 100644 index 6d92b196..00000000 --- a/15_virtual_mem_part3_precomputed_tables/src/time.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020-2022 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; - -//-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports -//-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - 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_part3_precomputed_tables/translation_table_tool/arch.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb similarity index 99% rename from 15_virtual_mem_part3_precomputed_tables/translation_table_tool/arch.rb rename to 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb index 07b06f13..44b8531e 100644 --- a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/arch.rb +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter # Bitfield manipulation. class BitField diff --git a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/bsp.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb similarity index 89% rename from 15_virtual_mem_part3_precomputed_tables/translation_table_tool/bsp.rb rename to 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb index 4aaedaf7..49e6fae9 100644 --- a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/bsp.rb +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb @@ -2,13 +2,13 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# 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('src/bsp/raspberrypi/memory.rs').split("\n") + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") def initialize @kernel_granule = Granule64KiB diff --git a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/generic.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb similarity index 98% rename from 15_virtual_mem_part3_precomputed_tables/translation_table_tool/generic.rb rename to 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb index 13df0658..743840e0 100644 --- a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/generic.rb +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter module Granule64KiB SIZE = 64 * 1024 @@ -151,7 +151,7 @@ def kernel_map_binary mapping_descriptors.each do |i| print 'Generating'.rjust(12).green.bold print ' ' - puts i.to_s + puts i TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) end diff --git a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/kernel_elf.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb similarity index 97% rename from 15_virtual_mem_part3_precomputed_tables/translation_table_tool/kernel_elf.rb rename to 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb index f2d5b0b7..5ba78d9d 100644 --- a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/kernel_elf.rb +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter # KernelELF class KernelELF diff --git a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/main.rb b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb similarity index 93% rename from 15_virtual_mem_part3_precomputed_tables/translation_table_tool/main.rb rename to 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb index 6419e364..22ab24fd 100755 --- a/15_virtual_mem_part3_precomputed_tables/translation_table_tool/main.rb +++ b/15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter require 'rubygems' require 'bundler/setup' diff --git a/16_virtual_mem_part4_higher_half_kernel/.vscode/settings.json b/16_virtual_mem_part4_higher_half_kernel/.vscode/settings.json index 0a8d7c09..9ef30cd0 100644 --- a/16_virtual_mem_part4_higher_half_kernel/.vscode/settings.json +++ b/16_virtual_mem_part4_higher_half_kernel/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 index a1766828..52d5b3fb 100644 --- a/16_virtual_mem_part4_higher_half_kernel/Cargo.lock +++ b/16_virtual_mem_part4_higher_half_kernel/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,8 +15,7 @@ dependencies = [ name = "mingo" version = "0.16.0" dependencies = [ - "cortex-a", - "mingo", + "aarch64-cpu", "qemu-exit", "test-macros", "test-types", @@ -25,11 +24,11 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.37" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" dependencies = [ - "unicode-xid", + "unicode-ident", ] [[package]] @@ -40,22 +39,22 @@ checksum = "9ff023245bfcc73fb890e1f8d5383825b3131cc920020a5c487d6f113dfc428a" [[package]] name = "quote" -version = "1.0.17" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "syn" -version = "1.0.91" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" dependencies = [ "proc-macro2", "quote", - "unicode-xid", + "unicode-ident", ] [[package]] @@ -74,12 +73,12 @@ version = "0.1.0" [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" [[package]] -name = "unicode-xid" -version = "0.2.2" +name = "unicode-ident" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" diff --git a/16_virtual_mem_part4_higher_half_kernel/Cargo.toml b/16_virtual_mem_part4_higher_half_kernel/Cargo.toml index 34f5090d..6480a727 100644 --- a/16_virtual_mem_part4_higher_half_kernel/Cargo.toml +++ b/16_virtual_mem_part4_higher_half_kernel/Cargo.toml @@ -1,67 +1,9 @@ -[package] -name = "mingo" -version = "0.16.0" -authors = ["Andre Richter "] -edition = "2021" +[workspace] + +members = [ + "libraries/*", + "kernel" +] [profile.release] lto = true - -[features] -default = [] -bsp_rpi3 = ["tock-registers"] -bsp_rpi4 = ["tock-registers"] -test_build = ["qemu-exit"] - -##-------------------------------------------------------------------------------------------------- -## Dependencies -##-------------------------------------------------------------------------------------------------- - -[dependencies] -test-types = { path = "test-types" } - -# Optional dependencies -tock-registers = { version = "0.7.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] -cortex-a = { version = "7.x.x" } - -##-------------------------------------------------------------------------------------------------- -## Testing -##-------------------------------------------------------------------------------------------------- - -[dev-dependencies] -test-macros = { path = "test-macros" } - -# The following line is a workaround, as suggested in [1], to enable a feature in test-builds only. -# This allows building the library part of the kernel with specialized code for testing. -# -# -# [1] https://github.com/rust-lang/cargo/issues/2911#issuecomment-749580481 -mingo = { path = ".", features = ["test_build"] } - -# 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/Makefile b/16_virtual_mem_part4_higher_half_kernel/Makefile index fec9097c..bc23270d 100644 --- a/16_virtual_mem_part4_higher_half_kernel/Makefile +++ b/16_virtual_mem_part4_higher_half_kernel/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -41,7 +42,7 @@ ifeq ($(BSP),rpi3) 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 + 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 @@ -55,7 +56,7 @@ else ifeq ($(BSP),rpi4) 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 + LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif @@ -67,16 +68,19 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -TT_TOOL_PATH = translation_table_tool - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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)) $(LAST_BUILD_CONFIG) +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)/*) @@ -101,11 +105,10 @@ COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release -RUSTC_CMD = cargo rustc $(COMPILER_ARGS) +RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) -CHECK_CMD = cargo check $(COMPILER_ARGS) -TEST_CMD = cargo test $(COMPILER_ARGS) +TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary @@ -183,7 +186,7 @@ $(KERNEL_BIN): $(KERNEL_ELF_TTABLES) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -219,6 +222,8 @@ chainboot: $(KERNEL_BIN) ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) + @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ + --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean @@ -241,7 +246,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -251,12 +255,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- @@ -293,6 +291,8 @@ gdb gdb-opt0: $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- .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: @@ -311,7 +311,11 @@ test_boot: $(KERNEL_BIN) ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER - #!/usr/bin/env bash +#!/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') diff --git a/16_virtual_mem_part4_higher_half_kernel/README.md b/16_virtual_mem_part4_higher_half_kernel/README.md index 52ca9bfe..8082ab45 100644 --- a/16_virtual_mem_part4_higher_half_kernel/README.md +++ b/16_virtual_mem_part4_higher_half_kernel/README.md @@ -78,8 +78,8 @@ type KernelTranslationTable = ### Linking Changes -In the `link.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 - +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: @@ -253,22 +253,22 @@ Minipush 1.0 Raspberry Pi 3 [ML] Requesting binary -[MP] ⏩ Pushing 259 KiB ======================================🦀 100% 129 KiB/s Time: 00:00:02 +[MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 [ML] Loaded! Executing the payload now -[ 2.893480] mingo version 0.16.0 -[ 2.893687] Booting on: Raspberry Pi 3 -[ 2.894142] MMU online: -[ 2.894434] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 2.896179] Virtual Physical Size Attr Entity -[ 2.897923] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 2.899668] 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.901282] 0xffff_ffff_c001_0000..0xffff_ffff_c004_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss -[ 2.902852] 0xffff_ffff_c086_0000..0xffff_ffff_c08d_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack -[ 2.904455] 0xffff_ffff_c005_0000..0xffff_ffff_c005_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM GPIO -[ 2.905907] | BCM PL011 UART -[ 2.907424] 0xffff_ffff_c006_0000..0xffff_ffff_c006_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Peripheral Interrupt Controller -[ 2.909168] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 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: @@ -303,31 +303,31 @@ Minipush 1.0 Raspberry Pi 4 [ML] Requesting binary -[MP] ⏩ Pushing 266 KiB ======================================🦀 100% 133 KiB/s Time: 00:00:02 +[MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 [ML] Loaded! Executing the payload now -[ 2.973300] mingo version 0.16.0 -[ 2.973334] Booting on: Raspberry Pi 4 -[ 2.973789] MMU online: -[ 2.974081] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 2.975825] Virtual Physical Size Attr Entity -[ 2.977569] ------------------------------------------------------------------------------------------------------------------------------------------- -[ 2.979314] 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.980929] 0xffff_ffff_c001_0000..0xffff_ffff_c004_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss -[ 2.982499] 0xffff_ffff_c086_0000..0xffff_ffff_c08d_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack -[ 2.984102] 0xffff_ffff_c005_0000..0xffff_ffff_c005_ffff --> 0x00_fe20_0000..0x00_fe20_ffff | 64 KiB | Dev RW XN | BCM GPIO -[ 2.985554] | BCM PL011 UART -[ 2.987070] 0xffff_ffff_c006_0000..0xffff_ffff_c006_ffff --> 0x00_ff84_0000..0x00_ff84_ffff | 64 KiB | Dev RW XN | GICD -[ 2.988479] | GICC -[ 2.989887] ------------------------------------------------------------------------------------------------------------------------------------------- +[ 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/Cargo.toml 16_virtual_mem_part4_higher_half_kernel/Cargo.toml ---- 15_virtual_mem_part3_precomputed_tables/Cargo.toml -+++ 16_virtual_mem_part4_higher_half_kernel/Cargo.toml +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" @@ -337,10 +337,10 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/Cargo.toml 16_virtual_mem_part edition = "2021" -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.rs ---- 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.rs -@@ -30,7 +30,10 @@ +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)] @@ -352,7 +352,7 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); -@@ -53,11 +56,11 @@ +@@ -57,11 +60,11 @@ ); // Second, let the link register point to kernel_init(). @@ -366,7 +366,7 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs } //-------------------------------------------------------------------------------------------------- -@@ -74,14 +77,19 @@ +@@ -78,14 +81,19 @@ #[no_mangle] pub unsafe extern "C" fn _start_rust( phys_kernel_tables_base_addr: u64, @@ -390,9 +390,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.rs asm::eret() } -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.s ---- 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s -+++ 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.s +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 @@ -409,10 +409,10 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s 1 + movk \register, #:abs_g0_nc:\symbol +.endm + - .equ _EL2, 0x8 - .equ _core_id_mask, 0b11 - -@@ -59,11 +71,23 @@ + //-------------------------------------------------------------------------------------------------- + // 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 @@ -432,8 +432,20 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s 1 + // 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 x4, __boot_core_stack_end_exclusive -+ mov sp, x4 ++ 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(). @@ -441,9 +453,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/cpu/boot.s 1 // Infinitely wait for events (aka "park the core"). -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu/translation_table.rs 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ---- 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu/translation_table.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +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)] @@ -515,9 +527,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu/t #[cfg(test)] mod tests { -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu.rs ---- 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu.rs +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 { @@ -568,79 +580,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/memory/mmu.r self.configure_translation_control(); -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/console.rs 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/console.rs ---- 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/console.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/console.rs -@@ -4,7 +4,6 @@ - - //! BSP console facilities. - --use super::memory; - use crate::{bsp::device_driver, console, cpu, driver}; - use core::fmt; - -@@ -26,21 +25,27 @@ - pub unsafe fn panic_console_out() -> impl fmt::Write { - use driver::interface::DeviceDriver; - -- let mut panic_gpio = device_driver::PanicGPIO::new(memory::map::mmio::GPIO_START.as_usize()); -- let mut panic_uart = -- device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.as_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(); -+ // If remapping of the driver's MMIO hasn't already happened, we won't be able to print. Just -+ // park the CPU core in this case. -+ let gpio_mmio_start_addr = match super::GPIO.virt_mmio_start_addr() { -+ None => cpu::wait_forever(), -+ Some(x) => x, -+ }; -+ -+ let uart_mmio_start_addr = match super::PL011_UART.virt_mmio_start_addr() { -+ None => cpu::wait_forever(), -+ Some(x) => x, -+ }; -+ -+ let mut panic_gpio = device_driver::PanicGPIO::new(gpio_mmio_start_addr); -+ let mut panic_uart = device_driver::PanicUart::new(uart_mmio_start_addr); - - panic_gpio -- .init(maybe_gpio_mmio_start_addr) -+ .init(None) - .unwrap_or_else(|_| cpu::wait_forever()); - panic_gpio.map_pl011_uart(); - panic_uart -- .init(maybe_uart_mmio_start_addr) -+ .init(None) - .unwrap_or_else(|_| cpu::wait_forever()); - - panic_uart -@@ -51,13 +56,14 @@ - pub unsafe fn panic_console_out() -> impl fmt::Write { - use driver::interface::DeviceDriver; - -- let mut panic_uart = -- device_driver::PanicUart::new(memory::map::mmio::PL011_UART_START.as_usize()); -- -- let maybe_uart_mmio_start_addr = super::PL011_UART.virt_mmio_start_addr(); -+ let uart_mmio_start_addr = match super::PL011_UART.virt_mmio_start_addr() { -+ None => cpu::wait_forever(), -+ Some(x) => x, -+ }; -+ let mut panic_uart = device_driver::PanicUart::new(uart_mmio_start_addr); - - panic_uart -- .init(maybe_uart_mmio_start_addr) -+ .init(None) - .unwrap_or_else(|_| cpu::qemu_exit_failure()); - - panic_uart - -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/link.ld ---- 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld -+++ 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/link.ld +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; @@ -668,8 +610,7 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld 16 SECTIONS { - . = __rpi_phys_dram_start_addr; -+ . = __kernel_virt_start_addr; - +- - /*********************************************************************************************** - * Boot Core Stack - ***********************************************************************************************/ @@ -681,7 +622,8 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld 16 - /* | 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") @@ -694,10 +636,11 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld 16 { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ -@@ -93,4 +88,23 @@ +@@ -91,6 +86,25 @@ + . += 8 * 1024 * 1024; __mmio_remap_end_exclusive = .; - ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") ++ ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + + /*********************************************************************************************** + * Guard Page @@ -716,12 +659,13 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/link.ld 16 + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + -+ ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") - } + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + + /*********************************************************************************************** -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory/mmu.rs ---- 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory/mmu.rs +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 @@ //-------------------------------------------------------------------------------------------------- @@ -760,9 +704,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory/mmu + ); } -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs ---- 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs +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: //! @@ -796,10 +740,10 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/bsp/raspberrypi/memory.rs pub mod mmu; -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/lib.rs 16_virtual_mem_part4_higher_half_kernel/src/lib.rs ---- 15_virtual_mem_part3_precomputed_tables/src/lib.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/lib.rs -@@ -150,11 +150,6 @@ +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 @@ ) } @@ -812,12 +756,12 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/lib.rs 16_virtual_mem_part // Testing //-------------------------------------------------------------------------------------------------- -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/translation_table.rs 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/translation_table.rs ---- 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/translation_table.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/translation_table.rs +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!(tables.init().is_ok()); + assert_eq!(tables.init(), Ok(())); - let virt_start_page_addr: PageAddress = PageAddress::from(0); - let virt_end_exclusive_page_addr: PageAddress = @@ -838,9 +782,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/translation_tab ); -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/types.rs 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/types.rs ---- 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/types.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/types.rs +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 //------------------------------------------------------------------------------ @@ -854,9 +798,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/types.rs 16_vir pub fn into_inner(self) -> Address { self.inner -diff -uNr 15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu.rs ---- 15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs -+++ 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu.rs +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: @@ -870,9 +814,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/src/memory/mmu.rs 16_virtual_m type TableStartFromBottom; } -diff -uNr 15_virtual_mem_part3_precomputed_tables/tests/02_exception_sync_page_fault.rs 16_virtual_mem_part4_higher_half_kernel/tests/02_exception_sync_page_fault.rs ---- 15_virtual_mem_part3_precomputed_tables/tests/02_exception_sync_page_fault.rs -+++ 16_virtual_mem_part4_higher_half_kernel/tests/02_exception_sync_page_fault.rs +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"); @@ -880,14 +824,14 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/tests/02_exception_sync_page_f - 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 = 1 * 1024 * 1024 * 1024; ++ 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/translation_table_tool/arch.rb 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/arch.rb ---- 15_virtual_mem_part3_precomputed_tables/translation_table_tool/arch.rb -+++ 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/arch.rb +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 @@ -898,9 +842,9 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/translation_table_tool/arch.rb lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT -diff -uNr 15_virtual_mem_part3_precomputed_tables/translation_table_tool/bsp.rb 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/bsp.rb ---- 15_virtual_mem_part3_precomputed_tables/translation_table_tool/bsp.rb -+++ 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/bsp.rb +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 @@ -908,7 +852,7 @@ diff -uNr 15_virtual_mem_part3_precomputed_tables/translation_table_tool/bsp.rb - 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('src/bsp/raspberrypi/memory.rs').split("\n") + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") @@ -14,6 +14,7 @@ @kernel_granule = Granule64KiB 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 00000000..857256cb --- /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/build.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/build.rs similarity index 100% rename from 16_virtual_mem_part4_higher_half_kernel/build.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/build.rs 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 00000000..2d010473 --- /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/src/_arch/aarch64/cpu/boot.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs similarity index 93% rename from 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs index 3d01b0dc..4d7b7735 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -12,12 +12,16 @@ //! crate::cpu::boot::arch_boot use crate::{memory, memory::Address}; +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; -use cortex_a::{asm, registers::*}; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Private Code diff --git a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.s b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s similarity index 88% rename from 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.s rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s index d2c9270d..1a8c8801 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu/boot.s +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s @@ -30,9 +30,6 @@ movk \register, #:abs_g0_nc:\symbol .endm -.equ _EL2, 0x8 -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -44,12 +41,12 @@ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL - cmp x0, _EL2 + 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, _core_id_mask + 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 @@ -84,8 +81,16 @@ _start: // 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 x4, __boot_core_stack_end_exclusive - mov sp, x4 + 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 diff --git a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/smp.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/smp.rs similarity index 88% rename from 13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/smp.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/smp.rs index 351fde62..49192038 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/_arch/aarch64/cpu/smp.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/smp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural symmetric multiprocessing. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::smp::arch_smp -use cortex_a::registers::*; +use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- 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 00000000..73019800 --- /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 00000000..91805ee7 --- /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/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception/asynchronous.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception/asynchronous.rs similarity index 79% rename from 15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception/asynchronous.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception/asynchronous.rs index 73b82e65..811ef138 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/_arch/aarch64/exception/asynchronous.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! @@ -11,8 +11,8 @@ //! //! crate::exception::asynchronous::arch_asynchronous +use aarch64_cpu::registers::*; use core::arch::asm; -use cortex_a::registers::*; use tock_registers::interfaces::{Readable, Writeable}; //-------------------------------------------------------------------------------------------------- @@ -83,42 +83,32 @@ pub fn is_local_irq_masked() -> bool { /// /// "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) - ); +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. -/// -/// # 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) - ); +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). -/// -/// # Safety -/// -/// - Changes the HW state of the executing core. #[inline(always)] -pub unsafe fn local_irq_mask_save() -> u64 { +pub fn local_irq_mask_save() -> u64 { let saved = DAIF.get(); local_irq_mask(); @@ -127,12 +117,11 @@ pub unsafe fn local_irq_mask_save() -> u64 { /// Restore the interrupt mask bits (DAIF) using the callee's argument. /// -/// # Safety +/// # Invariant /// -/// - Changes the HW state of the executing core. /// - No sanity checks on the input. #[inline(always)] -pub unsafe fn local_irq_restore(saved: u64) { +pub fn local_irq_restore(saved: u64) { DAIF.set(saved); } diff --git a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs similarity index 98% rename from 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs index 3d6c18b7..984b2e04 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! @@ -17,8 +17,8 @@ use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical}, }; +use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; -use cortex_a::{asm::barrier, registers::*}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- diff --git a/16_virtual_mem_part4_higher_half_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 similarity index 99% rename from 16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/memory/mmu/translation_table.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs index f0b4ac85..21fae3b8 100644 --- a/16_virtual_mem_part4_higher_half_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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! 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 00000000..ee1c3ef7 --- /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 00000000..246973bc --- /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/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver.rs similarity index 82% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver.rs index eafaf775..2dfaec8d 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/device_driver.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Device driver. diff --git a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/arm.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm.rs similarity index 64% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/arm.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm.rs index e83e24c9..8d1cbfbd 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/arm.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. diff --git a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/arm/gicv2.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2.rs similarity index 78% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/arm/gicv2.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2.rs index 4c68a692..256de704 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/arm/gicv2.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICv2 Driver - ARM Generic Interrupt Controller v2. //! @@ -79,36 +79,36 @@ mod gicc; mod gicd; -use crate::{bsp, cpu, driver, exception, memory, synchronization, synchronization::InitStateLock}; -use core::sync::atomic::{AtomicBool, Ordering}; +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, + synchronization::InitStateLock, +}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- -type HandlerTable = [Option; GICv2::NUM_IRQS]; +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. -pub type IRQNumber = exception::asynchronous::IRQNumber<{ GICv2::MAX_IRQ_NUMBER }>; +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; /// Representation of the GIC. pub struct GICv2 { - gicd_mmio_descriptor: memory::mmu::MMIODescriptor, - gicc_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, } @@ -119,24 +119,22 @@ pub struct GICv2 { 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; + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; /// Create an instance. /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. + /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new( - gicd_mmio_descriptor: memory::mmu::MMIODescriptor, - gicc_mmio_descriptor: memory::mmu::MMIODescriptor, + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, ) -> Self { Self { - gicd_mmio_descriptor, - gicc_mmio_descriptor, - gicd: gicd::GICD::new(gicd_mmio_descriptor.start_addr().as_usize()), - gicc: gicc::GICC::new(gicc_mmio_descriptor.start_addr().as_usize()), - is_mmio_remapped: AtomicBool::new(false), - handler_table: InitStateLock::new([None; Self::NUM_IRQS]), + 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]), } } } @@ -147,25 +145,13 @@ impl GICv2 { use synchronization::interface::ReadWriteEx; impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "GICv2 (ARM Generic Interrupt Controller v2)" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { - let remapped = self.is_mmio_remapped.load(Ordering::Relaxed); - if !remapped { - // GICD - let mut virt_addr = memory::mmu::kernel_map_mmio("GICD", &self.gicd_mmio_descriptor)?; - self.gicd.set_mmio(virt_addr.as_usize()); - - // GICC - virt_addr = memory::mmu::kernel_map_mmio("GICC", &self.gicc_mmio_descriptor)?; - self.gicc.set_mmio(virt_addr.as_usize()); - - // Conclude remapping. - self.is_mmio_remapped.store(true, Ordering::Relaxed); - } - if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { self.gicd.boot_core_init(); } @@ -182,23 +168,22 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { - let irq_number = irq_number.get(); + let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } - table[irq_number] = Some(descriptor); + table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } - fn enable(&self, irq_number: Self::IRQNumberType) { + fn enable(&self, irq_number: &Self::IRQNumberType) { self.gicd.enable(irq_number); } @@ -221,7 +206,7 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { 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"); + descriptor.handler().handle().expect("Error handling IRQ"); } } }); @@ -238,7 +223,7 @@ impl exception::asynchronous::interface::IRQManager for GICv2 { 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); + info!(" {: >3}. {}", i + 32, handler.name()); } } }); diff --git a/15_virtual_mem_part3_precomputed_tables/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 similarity index 79% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/arm/gicv2/gicc.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs index 1a151d24..0fd16bb3 100644 --- a/15_virtual_mem_part3_precomputed_tables/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 @@ -1,11 +1,13 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICC Driver - GIC CPU interface. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, exception, synchronization::InitStateLock, + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, }; use tock_registers::{ interfaces::{Readable, Writeable}, @@ -62,13 +64,12 @@ type Registers = MMIODerefWrapper; /// Representation of the GIC CPU interface. pub struct GICC { - registers: InitStateLock, + registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -use crate::synchronization::interface::ReadWriteEx; impl GICC { /// Create an instance. @@ -76,17 +77,12 @@ impl GICC { /// # 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: InitStateLock::new(Registers::new(mmio_start_addr)), + registers: 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: @@ -99,9 +95,7 @@ impl GICC { /// - 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. - }); + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. } /// Enable the interface - start accepting IRQs. @@ -111,9 +105,7 @@ impl GICC { /// - 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); - }); + self.registers.CTLR.write(CTLR::Enable::SET); } /// Extract the number of the highest-priority pending IRQ. @@ -129,8 +121,7 @@ impl GICC { &self, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) -> usize { - self.registers - .read(|regs| regs.IAR.read(IAR::InterruptID) as usize) + self.registers.IAR.read(IAR::InterruptID) as usize } /// Complete handling of the currently active IRQ. @@ -149,8 +140,6 @@ impl GICC { irq_number: u32, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) { - self.registers.read(|regs| { - regs.EOIR.write(EOIR::EOIINTID.val(irq_number)); - }); + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); } } diff --git a/14_virtual_mem_part2_mmio_remap/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 similarity index 85% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/arm/gicv2/gicd.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs index 60bbc468..1fc9d70e 100644 --- a/14_virtual_mem_part2_mmio_remap/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 @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! GICD Driver - GIC Distributor. //! @@ -9,8 +9,9 @@ use crate::{ bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, state, synchronization, - synchronization::{IRQSafeNullLock, InitStateLock}, + synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{Readable, Writeable}, @@ -51,9 +52,9 @@ register_structs! { (0x004 => TYPER: ReadOnly), (0x008 => _reserved1), (0x104 => ISENABLER: [ReadWrite; 31]), - (0x108 => _reserved2), + (0x180 => _reserved2), (0x820 => ITARGETSR: [ReadWrite; 248]), - (0x824 => @END), + (0xC00 => @END), } } @@ -64,7 +65,7 @@ register_structs! { (0x100 => ISENABLER: ReadWrite), (0x104 => _reserved2), (0x800 => ITARGETSR: [ReadOnly; 8]), - (0x804 => @END), + (0x820 => @END), } } @@ -84,7 +85,7 @@ pub struct GICD { shared_registers: IRQSafeNullLock, /// Access to banked registers is unguarded. - banked_registers: InitStateLock, + banked_registers: BankedRegisters, } //-------------------------------------------------------------------------------------------------- @@ -121,7 +122,6 @@ impl SharedRegisters { //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -use crate::synchronization::interface::ReadWriteEx; use synchronization::interface::Mutex; impl GICD { @@ -130,20 +130,13 @@ impl GICD { /// # 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: InitStateLock::new(BankedRegisters::new(mmio_start_addr)), + banked_registers: 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: @@ -151,8 +144,7 @@ impl GICD { /// "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)) + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) } /// Route all SPIs to the boot core and enable the distributor. @@ -180,7 +172,7 @@ impl GICD { } /// Enable an interrupt. - pub fn enable(&self, irq_num: super::IRQNumber) { + 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 @@ -191,10 +183,10 @@ impl GICD { // 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; + 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; diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm.rs similarity index 83% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm.rs index 5a7cc23b..7b7c288b 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. 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 00000000..812156f4 --- /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/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 similarity index 62% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs index 99961fac..62f07800 100644 --- a/16_virtual_mem_part4_higher_half_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 @@ -1,12 +1,18 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Interrupt Controller Driver. mod peripheral_ic; -use crate::{driver, exception, memory}; +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, +}; +use core::fmt; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -21,13 +27,12 @@ struct PendingIRQs { // Public Definitions //-------------------------------------------------------------------------------------------------- -pub type LocalIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; -pub type PeripheralIRQ = - exception::asynchronous::IRQNumber<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; +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), @@ -52,16 +57,13 @@ impl Iterator for PendingIRQs { type Item = usize; fn next(&mut self) -> Option { - use core::intrinsics::cttz; - - let next = cttz(self.bitmask); - if next == 64 { + if self.bitmask == 0 { return None; } - self.bitmask &= !(1 << next); - - Some(next as usize) + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) } } @@ -69,22 +71,30 @@ impl Iterator for PendingIRQs { // 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 { - const MAX_LOCAL_IRQ_NUMBER: usize = 11; + // 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; - const NUM_PERIPHERAL_IRQS: usize = Self::MAX_PERIPHERAL_IRQ_NUMBER + 1; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; /// Create an instance. /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new( - _local_mmio_descriptor: memory::mmu::MMIODescriptor, - periph_mmio_descriptor: memory::mmu::MMIODescriptor, - ) -> Self { + /// - 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_descriptor), + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), } } } @@ -94,12 +104,10 @@ impl InterruptController { //------------------------------------------------------------------------------ impl driver::interface::DeviceDriver for InterruptController { - fn compatible(&self) -> &'static str { - "BCM Interrupt Controller" - } + type IRQNumberType = IRQNumber; - unsafe fn init(&self) -> Result<(), &'static str> { - self.periph.init() + fn compatible(&self) -> &'static str { + Self::COMPATIBLE } } @@ -108,16 +116,23 @@ impl exception::asynchronous::interface::IRQManager for InterruptController { fn register_handler( &self, - irq: Self::IRQNumberType, - descriptor: exception::asynchronous::IRQDescriptor, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { - match irq { + match irq_handler_descriptor.number() { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), - IRQNumber::Peripheral(pirq) => self.periph.register_handler(pirq, 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) { + fn enable(&self, irq: &Self::IRQNumberType) { match irq { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), 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 00000000..a26bff8d --- /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 00000000..b424d4be --- /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 00000000..3ce1d8d8 --- /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 00000000..30421dfa --- /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 00000000..65cf5abb --- /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 00000000..a1f55b17 --- /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/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception.rs similarity index 67% rename from 13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception.rs index aa6c5a63..a9eaa6ac 100644 --- a/13_exceptions_part2_peripheral_IRQs/src/bsp/raspberrypi/exception.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. diff --git a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/exception/asynchronous.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception/asynchronous.rs similarity index 56% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/exception/asynchronous.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception/asynchronous.rs index dc5ab421..776182fd 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/exception/asynchronous.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -1,15 +1,18 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! BSP asynchronous exception handling. -use crate::{bsp, exception}; +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}; @@ -23,14 +26,3 @@ pub(in crate::bsp) mod irq_map { 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/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/link.ld b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld similarity index 91% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/link.ld rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld index 14619829..c17b61f9 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/link.ld +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld @@ -57,7 +57,6 @@ SECTIONS } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code - .got : ALIGN(8) { *(.got) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; @@ -107,4 +106,12 @@ SECTIONS } :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/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 similarity index 100% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld diff --git a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs similarity index 97% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs index 9e071726..3a33126c 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! @@ -111,9 +111,6 @@ pub(super) mod map { 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 --git a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory/mmu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs similarity index 99% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory/mmu.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs index bfebd8b2..3c0368b9 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/memory/mmu.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. diff --git a/16_virtual_mem_part4_higher_half_kernel/src/common.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/common.rs similarity index 54% rename from 16_virtual_mem_part4_higher_half_kernel/src/common.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/common.rs index 678f4a6c..2ad7e4c1 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/common.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/common.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! General purpose code. @@ -27,3 +27,20 @@ pub const fn align_up(value: usize, alignment: usize) -> usize { (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 00000000..f0363464 --- /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 00000000..e92a022b --- /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/15_virtual_mem_part3_precomputed_tables/src/cpu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu.rs similarity index 89% rename from 15_virtual_mem_part3_precomputed_tables/src/cpu.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu.rs index e1493d1d..8716a918 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/cpu.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. 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 00000000..b1e98328 --- /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/15_virtual_mem_part3_precomputed_tables/src/cpu/smp.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/smp.rs similarity index 87% rename from 15_virtual_mem_part3_precomputed_tables/src/cpu/smp.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/smp.rs index 57386f79..de612d58 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/cpu/smp.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/smp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Symmetric multiprocessing. 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 00000000..2edf8b85 --- /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 00000000..3d5f219f --- /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/src/exception/asynchronous.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous.rs similarity index 63% rename from 16_virtual_mem_part4_higher_half_kernel/src/exception/asynchronous.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous.rs index fb1785c2..2c874dd6 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/exception/asynchronous.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous.rs @@ -1,14 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// 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 core::{fmt, marker::PhantomData}; +use crate::{bsp, synchronization}; +use core::marker::PhantomData; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports @@ -22,14 +24,23 @@ pub use arch_asynchronous::{ // Public Definitions //-------------------------------------------------------------------------------------------------- +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + /// Interrupt descriptor. #[derive(Copy, Clone)] -pub struct IRQDescriptor { +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + /// Descriptive name. - pub name: &'static str, + name: &'static str, /// Reference to handler trait object. - pub handler: &'static (dyn interface::IRQHandler + Sync), + handler: &'static (dyn interface::IRQHandler + Sync), } /// IRQContext token. @@ -59,17 +70,16 @@ pub mod interface { /// platform's interrupt controller. pub trait IRQManager { /// The IRQ number type depends on the implementation. - type IRQNumberType; + type IRQNumberType: Copy; /// Register a handler. fn register_handler( &self, - irq_number: Self::IRQNumberType, - descriptor: super::IRQDescriptor, + irq_handler_descriptor: super::IRQHandlerDescriptor, ) -> Result<(), &'static str>; /// Enable an interrupt in the controller. - fn enable(&self, irq_number: Self::IRQNumberType); + fn enable(&self, irq_number: &Self::IRQNumberType); /// Handle pending interrupts. /// @@ -85,17 +95,55 @@ pub mod interface { ); /// Print list of registered handlers. - fn print_handler(&self); + fn print_handler(&self) {} } } -/// A wrapper type for IRQ numbers with integrated range sanity check. -#[derive(Copy, Clone)] -pub struct IRQNumber(usize); +//-------------------------------------------------------------------------------------------------- +// 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. @@ -114,39 +162,29 @@ impl<'irq_context> IRQContext<'irq_context> { } } -impl IRQNumber<{ 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 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); - } + 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 00000000..38919ffe --- /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/src/lib.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs similarity index 94% rename from 16_virtual_mem_part4_higher_half_kernel/src/lib.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs index 76cd3792..d883d354 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/lib.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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` library. //! @@ -109,13 +111,18 @@ #![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)] @@ -175,8 +182,8 @@ pub fn test_runner(tests: &[&test_types::UnitTest]) { #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); test_main(); 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 00000000..e41cfaa0 --- /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/src/memory.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory.rs similarity index 90% rename from 16_virtual_mem_part4_higher_half_kernel/src/memory.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory.rs index b5aa666d..6131bdb6 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/memory.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Memory Management. @@ -18,18 +18,18 @@ use core::{ //-------------------------------------------------------------------------------------------------- /// Metadata trait for marking the type of an address. -pub trait AddressType: Copy + Clone + PartialOrd + PartialEq {} +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} /// Zero-sized type to mark a physical address. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[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)] +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub enum Virtual {} /// Generic address type. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub struct Address { value: usize, _address_type: PhantomData ATYPE>, @@ -136,6 +136,11 @@ impl fmt::Display for Address { } } +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); +} + //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- @@ -160,7 +165,7 @@ mod tests { bsp::memory::mmu::KernelGranule::SIZE * 2 ); - assert_eq!(addr.is_page_aligned(), false); + assert!(!addr.is_page_aligned()); assert_eq!(addr.offset_into_page(), 100); } diff --git a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs similarity index 95% rename from 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs index dfc29993..404e2a8a 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. @@ -8,8 +8,8 @@ #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; -mod alloc; mod mapping_record; +mod page_alloc; mod translation_table; mod types; @@ -82,14 +82,6 @@ use interface::MMU; 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(); - - alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.initialize(region)); -} - /// Map a region in the kernel's translation tables. /// /// No input checks done, input is passed through to the architectural implementation. @@ -169,6 +161,14 @@ impl AddressSpace { } } +/// 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, @@ -208,7 +208,7 @@ pub unsafe fn kernel_map_mmio( }; let virt_region = - alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; kernel_map_at_unchecked( name, @@ -247,6 +247,11 @@ pub fn try_kernel_page_attributes( .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 @@ -258,13 +263,3 @@ pub unsafe fn enable_mmu_and_caching( ) -> 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() -} diff --git a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu/mapping_record.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/mapping_record.rs similarity index 90% rename from 15_virtual_mem_part3_precomputed_tables/src/memory/mmu/mapping_record.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/mapping_record.rs index d171c6e6..0e079220 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/memory/mmu/mapping_record.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/mapping_record.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! A record of mapped pages. @@ -8,7 +8,7 @@ use super::{ AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, Physical, Virtual, }; -use crate::{bsp, info, synchronization, synchronization::InitStateLock, warn}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -76,6 +76,19 @@ impl MappingRecord { 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); @@ -90,8 +103,7 @@ impl MappingRecord { ) -> Option<&mut MappingRecordEntry> { self.inner .iter_mut() - .filter(|x| x.is_some()) - .map(|x| x.as_mut().unwrap()) + .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() { @@ -121,13 +133,13 @@ impl MappingRecord { phys_region, attr, )); + + self.sort(); + Ok(()) } pub fn print(&self) { - const KIB_RSHIFT: u32 = 10; // log2(1024). - const MIB_RSHIFT: u32 = 20; // log2(1024 * 1024). - info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); info!( " {:^44} {:^30} {:^7} {:^9} {:^35}", @@ -142,13 +154,7 @@ impl MappingRecord { let phys_start = i.phys_start_addr; let phys_end_inclusive = phys_start + (size - 1); - 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 (size, unit) = common::size_human_readable_ceil(size); let attr = match i.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", @@ -167,8 +173,7 @@ impl MappingRecord { }; info!( - " {}..{} --> {}..{} | \ - {: >3} {} | {: <3} {} {: <2} | {}", + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", virt_start, virt_end_inclusive, phys_start, diff --git a/14_virtual_mem_part2_mmio_remap/src/memory/mmu/alloc.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/page_alloc.rs similarity index 93% rename from 14_virtual_mem_part2_mmio_remap/src/memory/mmu/alloc.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/page_alloc.rs index aadb72ef..344afd20 100644 --- a/14_virtual_mem_part2_mmio_remap/src/memory/mmu/alloc.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/page_alloc.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter -//! Allocation. +//! Page allocation. use super::MemoryRegion; use crate::{ @@ -44,7 +44,7 @@ impl PageAllocator { } /// Initialize the allocator. - pub fn initialize(&mut self, pool: MemoryRegion) { + pub fn init(&mut self, pool: MemoryRegion) { if self.pool.is_some() { warn!("Already initialized"); return; diff --git a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/translation_table.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs similarity index 98% rename from 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/translation_table.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs index 9d627f97..341ffc5c 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/translation_table.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Translation table. @@ -97,7 +97,7 @@ mod tests { // This will occupy a lot of space on the stack. let mut tables = MinSizeTranslationTable::new_for_runtime(); - assert!(tables.init().is_ok()); + assert_eq!(tables.init(), Ok(())); let virt_end_exclusive_page_addr: PageAddress = PageAddress::MAX; let virt_start_page_addr: PageAddress = diff --git a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/types.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs similarity index 95% rename from 16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/types.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs index b72ece28..f6ac8d59 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/memory/mmu/types.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit types. @@ -15,13 +15,13 @@ use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; //-------------------------------------------------------------------------------------------------- /// A wrapper type around [Address] that ensures page alignment. -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[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, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct MemoryRegion { start: PageAddress, end_exclusive: PageAddress, @@ -29,7 +29,7 @@ pub struct MemoryRegion { /// Architecture agnostic memory attributes. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum MemAttributes { CacheableDRAM, Device, @@ -37,7 +37,7 @@ pub enum MemAttributes { /// Architecture agnostic access permissions. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum AccessPermissions { ReadOnly, ReadWrite, @@ -45,7 +45,7 @@ pub enum AccessPermissions { /// Collection of memory attributes. #[allow(missing_docs)] -#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, @@ -368,13 +368,11 @@ mod tests { assert_eq!(allocation.num_pages(), 2); assert_eq!(three_region.num_pages(), 1); - let mut count = 0; - for i in allocation.into_iter() { + for (i, alloc) in allocation.into_iter().enumerate() { assert_eq!( - i.into_inner().as_usize(), - count * bsp::memory::mmu::KernelGranule::SIZE + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE ); - count = count + 1; } } } diff --git a/14_virtual_mem_part2_mmio_remap/src/panic_wait.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/panic_wait.rs similarity index 78% rename from 14_virtual_mem_part2_mmio_remap/src/panic_wait.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/panic_wait.rs index 08d7d453..c6f3a9c7 100644 --- a/14_virtual_mem_part2_mmio_remap/src/panic_wait.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/panic_wait.rs @@ -1,22 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. -use crate::{bsp, cpu, exception}; -use core::{fmt, panic::PanicInfo}; +use crate::{cpu, exception, println}; +use core::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 `libkernel`. /// /// It is linked weakly, so that the integration tests can overload its standard behavior. @@ -34,16 +28,6 @@ fn _panic_exit() -> ! { } } -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -75,9 +59,7 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - - unsafe { exception::asynchronous::local_irq_mask() }; + exception::asynchronous::local_irq_mask(); // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -88,7 +70,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", 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 00000000..8e303046 --- /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/src/state.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/state.rs similarity index 97% rename from 16_virtual_mem_part4_higher_half_kernel/src/state.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/state.rs index 0af3688c..6d99beed 100644 --- a/16_virtual_mem_part4_higher_half_kernel/src/state.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/state.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! State information about the kernel itself. diff --git a/15_virtual_mem_part3_precomputed_tables/src/synchronization.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/src/synchronization.rs similarity index 89% rename from 15_virtual_mem_part3_precomputed_tables/src/synchronization.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/src/synchronization.rs index 4b4c4c3f..5740b63e 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/synchronization.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } /// A reader-writer exclusion type. @@ -38,10 +38,10 @@ pub mod interface { type Data; /// Grants temporary mutable access to the encapsulated data. - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R; + 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(&self, f: impl FnOnce(&Self::Data) -> R) -> R; + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; } } @@ -105,7 +105,7 @@ use crate::{exception, state}; impl interface::Mutex for IRQSafeNullLock { 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() }; @@ -118,7 +118,7 @@ impl interface::Mutex for IRQSafeNullLock { impl interface::ReadWriteEx for InitStateLock { type Data = T; - fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { + 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" @@ -133,7 +133,7 @@ impl interface::ReadWriteEx for InitStateLock { f(data) } - fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { let data = unsafe { &*self.data.get() }; f(data) 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 00000000..a9d50120 --- /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 00000000..8be7a2f1 --- /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/15_virtual_mem_part3_precomputed_tables/tests/00_console_sanity.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rs similarity index 79% rename from 15_virtual_mem_part3_precomputed_tables/tests/00_console_sanity.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rs index 6595aac1..682ea9b8 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/00_console_sanity.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Console sanity tests - RX, TX and statistics. @@ -15,12 +15,11 @@ use libkernel::{bsp, console, cpu, exception, memory, print}; #[no_mangle] unsafe fn kernel_init() -> ! { - use bsp::console::console; - use console::interface::*; + use console::console; exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); diff --git a/15_virtual_mem_part3_precomputed_tables/tests/01_timer_sanity.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/01_timer_sanity.rs similarity index 81% rename from 15_virtual_mem_part3_precomputed_tables/tests/01_timer_sanity.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/tests/01_timer_sanity.rs index 9b2b228d..1581a02e 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/01_timer_sanity.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/01_timer_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Timer sanity tests. @@ -11,14 +11,14 @@ #![test_runner(libkernel::test_runner)] use core::time::Duration; -use libkernel::{bsp, cpu, exception, memory, time, time::interface::TimeManager}; +use libkernel::{bsp, cpu, exception, memory, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + 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. @@ -36,6 +36,7 @@ fn timer_is_counting() { /// 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) } diff --git a/16_virtual_mem_part4_higher_half_kernel/tests/02_exception_sync_page_fault.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs similarity index 85% rename from 16_virtual_mem_part4_higher_half_kernel/tests/02_exception_sync_page_fault.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs index 71b63e21..09d17798 100644 --- a/16_virtual_mem_part4_higher_half_kernel/tests/02_exception_sync_page_fault.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. @@ -22,14 +22,14 @@ use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + 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 = 1 * 1024 * 1024 * 1024; + 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 --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 00000000..02f51f74 --- /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/15_virtual_mem_part3_precomputed_tables/tests/03_exception_restore_sanity.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rs similarity index 88% rename from 15_virtual_mem_part3_precomputed_tables/tests/03_exception_restore_sanity.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rs index 983d488f..1a302911 100644 --- a/15_virtual_mem_part3_precomputed_tables/tests/03_exception_restore_sanity.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2022 Andre Richter +// Copyright (c) 2022-2023 Andre Richter //! A simple sanity test to see if exception restore code works. @@ -31,8 +31,8 @@ fn nested_system_call() { #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); diff --git a/16_virtual_mem_part4_higher_half_kernel/tests/04_exception_irq_sanity.rs b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/04_exception_irq_sanity.rs similarity index 69% rename from 16_virtual_mem_part4_higher_half_kernel/tests/04_exception_irq_sanity.rs rename to 16_virtual_mem_part4_higher_half_kernel/kernel/tests/04_exception_irq_sanity.rs index 9030424d..fcace897 100644 --- a/16_virtual_mem_part4_higher_half_kernel/tests/04_exception_irq_sanity.rs +++ b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/04_exception_irq_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! IRQ handling sanity tests. @@ -15,8 +15,8 @@ use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { - memory::mmu::post_enable_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); exception::handling_init(); exception::asynchronous::local_irq_unmask(); @@ -32,21 +32,21 @@ fn local_irq_mask_works() { // Precondition: IRQs are unmasked. assert!(exception::asynchronous::is_local_irq_masked()); - unsafe { exception::asynchronous::local_irq_mask() }; + exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); // Restore earlier state. - unsafe { exception::asynchronous::local_irq_unmask() }; + 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() }; + exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); - unsafe { exception::asynchronous::local_irq_unmask() }; + exception::asynchronous::local_irq_unmask(); assert!(exception::asynchronous::is_local_irq_masked()); } @@ -56,12 +56,12 @@ 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() }; + let first = exception::asynchronous::local_irq_mask_save(); assert!(!exception::asynchronous::is_local_irq_masked()); - let second = unsafe { exception::asynchronous::local_irq_mask_save() }; + let second = exception::asynchronous::local_irq_mask_save(); assert_ne!(first, second); - unsafe { exception::asynchronous::local_irq_restore(first) }; + exception::asynchronous::local_irq_restore(first); assert!(exception::asynchronous::is_local_irq_masked()); } diff --git a/16_virtual_mem_part4_higher_half_kernel/tests/boot_test_string.rb b/16_virtual_mem_part4_higher_half_kernel/kernel/tests/boot_test_string.rb similarity index 100% rename from 16_virtual_mem_part4_higher_half_kernel/tests/boot_test_string.rb rename to 16_virtual_mem_part4_higher_half_kernel/kernel/tests/boot_test_string.rb 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 00000000..449ad6f9 --- /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 00000000..9ac19144 --- /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/test-macros/Cargo.toml b/16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/Cargo.toml similarity index 100% rename from 16_virtual_mem_part4_higher_half_kernel/test-macros/Cargo.toml rename to 16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/Cargo.toml 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 00000000..52cf893d --- /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/test-types/Cargo.toml b/16_virtual_mem_part4_higher_half_kernel/libraries/test-types/Cargo.toml similarity index 100% rename from 16_virtual_mem_part4_higher_half_kernel/test-types/Cargo.toml rename to 16_virtual_mem_part4_higher_half_kernel/libraries/test-types/Cargo.toml 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 00000000..38961a9c --- /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/src/_arch/aarch64/cpu.rs b/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu.rs deleted file mode 100644 index 66da661c..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/cpu.rs +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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 cortex_a::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/src/_arch/aarch64/exception.rs b/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/exception.rs deleted file mode 100644 index 495dba34..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/exception.rs +++ /dev/null @@ -1,315 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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::{bsp, exception}; -use core::{arch::global_asm, cell::UnsafeCell, fmt}; -use cortex_a::{asm::barrier, registers::*}; -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] -unsafe 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] -unsafe 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] -unsafe 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] -unsafe 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] -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); -} - -//------------------------------------------------------------------------------ -// 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/src/_arch/aarch64/exception.s b/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/exception.s deleted file mode 100644 index 5aae30b9..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/exception.s +++ /dev/null @@ -1,150 +0,0 @@ -// 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 - // 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 -.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/src/_arch/aarch64/time.rs b/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/time.rs deleted file mode 100644 index c814219c..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/_arch/aarch64/time.rs +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -const NS_PER_S: u64 = 1_000_000_000; - -/// ARMv8 Generic Timer. -struct GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static TIME_MANAGER: GenericTimer = GenericTimer; - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } -} - -//-------------------------------------------------------------------------------------------------- -// 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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; - - 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) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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/16_virtual_mem_part4_higher_half_kernel/src/bsp.rs b/16_virtual_mem_part4_higher_half_kernel/src/bsp.rs deleted file mode 100644 index 824787f6..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp.rs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs b/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs deleted file mode 100644 index eea07b75..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ /dev/null @@ -1,259 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 Andre Richter - -//! GPIO Driver. - -use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, memory, synchronization, - synchronization::IRQSafeNullLock, -}; -use core::sync::atomic::{AtomicUsize, Ordering}; -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; - -//-------------------------------------------------------------------------------------------------- -// 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 { - 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(mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { - Self { - mmio_descriptor, - virt_mmio_start_addr: AtomicUsize::new(0), - inner: IRQSafeNullLock::new(GPIOInner::new(mmio_descriptor.start_addr().as_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.mmio_descriptor)?; - - self.inner - .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; - - self.virt_mmio_start_addr - .store(virt_addr.as_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/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/common.rs b/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/common.rs deleted file mode 100644 index fd9e988e..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/common.rs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020-2022 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/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi.rs b/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi.rs deleted file mode 100644 index fb9edf88..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi.rs +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/console.rs b/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/console.rs deleted file mode 100644 index e75f5fda..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/console.rs +++ /dev/null @@ -1,94 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 Andre Richter - -//! BSP console facilities. - -use crate::{bsp::device_driver, console, cpu, driver}; -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. -#[cfg(not(feature = "test_build"))] -pub unsafe fn panic_console_out() -> impl fmt::Write { - use driver::interface::DeviceDriver; - - // If remapping of the driver's MMIO hasn't already happened, we won't be able to print. Just - // park the CPU core in this case. - let gpio_mmio_start_addr = match super::GPIO.virt_mmio_start_addr() { - None => cpu::wait_forever(), - Some(x) => x, - }; - - let uart_mmio_start_addr = match super::PL011_UART.virt_mmio_start_addr() { - None => cpu::wait_forever(), - Some(x) => x, - }; - - let mut panic_gpio = device_driver::PanicGPIO::new(gpio_mmio_start_addr); - let mut panic_uart = device_driver::PanicUart::new(uart_mmio_start_addr); - - panic_gpio - .init(None) - .unwrap_or_else(|_| cpu::wait_forever()); - panic_gpio.map_pl011_uart(); - panic_uart - .init(None) - .unwrap_or_else(|_| cpu::wait_forever()); - - panic_uart -} - -/// Reduced version for test builds. -#[cfg(feature = "test_build")] -pub unsafe fn panic_console_out() -> impl fmt::Write { - use driver::interface::DeviceDriver; - - let uart_mmio_start_addr = match super::PL011_UART.virt_mmio_start_addr() { - None => cpu::wait_forever(), - Some(x) => x, - }; - let mut panic_uart = device_driver::PanicUart::new(uart_mmio_start_addr); - - panic_uart - .init(None) - .unwrap_or_else(|_| cpu::qemu_exit_failure()); - - 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. -#[cfg(feature = "test_build")] -pub fn qemu_bring_up_console() { - use driver::interface::DeviceDriver; - - // Calling the UART's init ensures that the BSP's instance of the UART does remap the MMIO - // addresses. - unsafe { - super::PL011_UART - .init() - .unwrap_or_else(|_| cpu::qemu_exit_failure()); - } -} diff --git a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/cpu.rs b/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/cpu.rs deleted file mode 100644 index 85fb89e4..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/cpu.rs +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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/src/bsp/raspberrypi/driver.rs b/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/driver.rs deleted file mode 100644 index 53168752..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/bsp/raspberrypi/driver.rs +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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/16_virtual_mem_part4_higher_half_kernel/src/console.rs b/16_virtual_mem_part4_higher_half_kernel/src/console.rs deleted file mode 100644 index e49e241f..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/console.rs +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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 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; -} diff --git a/16_virtual_mem_part4_higher_half_kernel/src/cpu/boot.rs b/16_virtual_mem_part4_higher_half_kernel/src/cpu/boot.rs deleted file mode 100644 index 8091dac3..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/cpu/boot.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2021-2022 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/src/driver.rs b/16_virtual_mem_part4_higher_half_kernel/src/driver.rs deleted file mode 100644 index 7b800dbc..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/driver.rs +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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/16_virtual_mem_part4_higher_half_kernel/src/exception.rs b/16_virtual_mem_part4_higher_half_kernel/src/exception.rs deleted file mode 100644 index f4af8144..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/exception.rs +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020-2022 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(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/src/main.rs b/16_virtual_mem_part4_higher_half_kernel/src/main.rs deleted file mode 100644 index 8bc80885..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/main.rs +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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. -/// -/// 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() -> ! { - use driver::interface::DriverManager; - - exception::handling_init(); - memory::mmu::post_enable_init(); - - // Add the mapping records for the precomputed entries first, so that they appear on the top of - // the list. - bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); - - // 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 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!("{}", 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:"); - 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/16_virtual_mem_part4_higher_half_kernel/src/panic_wait.rs b/16_virtual_mem_part4_higher_half_kernel/src/panic_wait.rs deleted file mode 100644 index 08d7d453..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/panic_wait.rs +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 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 `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() - } -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - -/// 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) -> ! { - use crate::time::interface::TimeManager; - - unsafe { 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), - }; - - panic_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/src/print.rs b/16_virtual_mem_part4_higher_half_kernel/src/print.rs deleted file mode 100644 index 9ec13a28..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/print.rs +++ /dev/null @@ -1,94 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2022 Andre Richter - -//! Printing. - -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 -#[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) => ({ - use $crate::time::interface::TimeManager; - - 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)*) => ({ - use $crate::time::interface::TimeManager; - - 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) => ({ - use $crate::time::interface::TimeManager; - - 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)*) => ({ - use $crate::time::interface::TimeManager; - - 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/src/time.rs b/16_virtual_mem_part4_higher_half_kernel/src/time.rs deleted file mode 100644 index 6d92b196..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/src/time.rs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2020-2022 Andre Richter - -//! Timer primitives. - -#[cfg(target_arch = "aarch64")] -#[path = "_arch/aarch64/time.rs"] -mod arch_time; - -//-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports -//-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; - - /// Time management functions. - 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/16_virtual_mem_part4_higher_half_kernel/test-macros/src/lib.rs b/16_virtual_mem_part4_higher_half_kernel/test-macros/src/lib.rs deleted file mode 100644 index 83025a09..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/test-macros/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2022 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/16_virtual_mem_part4_higher_half_kernel/test-types/src/lib.rs b/16_virtual_mem_part4_higher_half_kernel/test-types/src/lib.rs deleted file mode 100644 index 922c2a1c..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/test-types/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2022 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/tests/00_console_sanity.rb b/16_virtual_mem_part4_higher_half_kernel/tests/00_console_sanity.rb deleted file mode 100644 index 48c9703d..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/tests/00_console_sanity.rb +++ /dev/null @@ -1,48 +0,0 @@ -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2019-2022 Andre Richter - -require_relative '../../common/tests/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/tests/03_exception_restore_sanity.rb b/16_virtual_mem_part4_higher_half_kernel/tests/03_exception_restore_sanity.rb deleted file mode 100644 index c3c725ed..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/tests/03_exception_restore_sanity.rb +++ /dev/null @@ -1,25 +0,0 @@ -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2022 Andre Richter - -require_relative '../../common/tests/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/tests/panic_exit_success/mod.rs b/16_virtual_mem_part4_higher_half_kernel/tests/panic_exit_success/mod.rs deleted file mode 100644 index 908fac51..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/tests/panic_exit_success/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2019-2022 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/tests/panic_wait_forever/mod.rs b/16_virtual_mem_part4_higher_half_kernel/tests/panic_wait_forever/mod.rs deleted file mode 100644 index 7a4effa5..00000000 --- a/16_virtual_mem_part4_higher_half_kernel/tests/panic_wait_forever/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2022 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/translation_table_tool/arch.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb similarity index 99% rename from 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/arch.rb rename to 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb index deceb6d0..61a6d6ca 100644 --- a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/arch.rb +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter # Bitfield manipulation. class BitField diff --git a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/bsp.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb similarity index 90% rename from 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/bsp.rb rename to 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb index ddf69a17..93bcedd9 100644 --- a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/bsp.rb +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb @@ -2,13 +2,13 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# 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('src/bsp/raspberrypi/memory.rs').split("\n") + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") def initialize @kernel_granule = Granule64KiB diff --git a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/generic.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/generic.rb similarity index 98% rename from 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/generic.rb rename to 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/generic.rb index 13df0658..743840e0 100644 --- a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/generic.rb +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/generic.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter module Granule64KiB SIZE = 64 * 1024 @@ -151,7 +151,7 @@ def kernel_map_binary mapping_descriptors.each do |i| print 'Generating'.rjust(12).green.bold print ' ' - puts i.to_s + puts i TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) end diff --git a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/kernel_elf.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/kernel_elf.rb similarity index 97% rename from 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/kernel_elf.rb rename to 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/kernel_elf.rb index f2d5b0b7..5ba78d9d 100644 --- a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/kernel_elf.rb +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/kernel_elf.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter # KernelELF class KernelELF diff --git a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/main.rb b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/main.rb similarity index 93% rename from 16_virtual_mem_part4_higher_half_kernel/translation_table_tool/main.rb rename to 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/main.rb index 6419e364..22ab24fd 100755 --- a/16_virtual_mem_part4_higher_half_kernel/translation_table_tool/main.rb +++ b/16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/main.rb @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter require 'rubygems' require 'bundler/setup' diff --git a/17_kernel_symbols/.cargo/config.toml b/17_kernel_symbols/.cargo/config.toml new file mode 100644 index 00000000..e3476485 --- /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 00000000..9ef30cd0 --- /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 00000000..382a3bda --- /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 00000000..1ea72c9f --- /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 00000000..3c33cd66 --- /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 00000000..78962bd8 --- /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 00000000..58bf54d2 --- /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 00000000..cab00bb3 --- /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 00000000..2d010473 --- /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 00000000..4d7b7735 --- /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 00000000..1a8c8801 --- /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 00000000..49192038 --- /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 00000000..d7863a1e --- /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 00000000..91805ee7 --- /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 00000000..811ef138 --- /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 00000000..984b2e04 --- /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 00000000..21fae3b8 --- /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 00000000..ee1c3ef7 --- /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 00000000..246973bc --- /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 00000000..2dfaec8d --- /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 00000000..8d1cbfbd --- /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 00000000..256de704 --- /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 00000000..0fd16bb3 --- /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 00000000..1fc9d70e --- /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 00000000..7b7c288b --- /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 00000000..812156f4 --- /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 00000000..62f07800 --- /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 00000000..a26bff8d --- /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 00000000..b424d4be --- /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 00000000..3ce1d8d8 --- /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 00000000..30421dfa --- /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 00000000..65cf5abb --- /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 00000000..a1f55b17 --- /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 00000000..a9eaa6ac --- /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 00000000..776182fd --- /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 00000000..193a5200 --- /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 00000000..c5d58c30 --- /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 00000000..96a4d8c1 --- /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 00000000..3c0368b9 --- /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 00000000..2ad7e4c1 --- /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 00000000..f0363464 --- /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 00000000..e92a022b --- /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 00000000..8716a918 --- /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 00000000..b1e98328 --- /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 00000000..de612d58 --- /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 00000000..2edf8b85 --- /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 00000000..3d5f219f --- /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 00000000..2c874dd6 --- /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 00000000..38919ffe --- /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 00000000..54e581a2 --- /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 00000000..e41cfaa0 --- /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 00000000..6131bdb6 --- /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 00000000..404e2a8a --- /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 00000000..0e079220 --- /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 00000000..344afd20 --- /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 00000000..341ffc5c --- /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 00000000..f6ac8d59 --- /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 00000000..c6f3a9c7 --- /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 00000000..8e303046 --- /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 00000000..6d99beed --- /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 00000000..fdc1d084 --- /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 00000000..5740b63e --- /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 00000000..a9d50120 --- /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 00000000..8be7a2f1 --- /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/12_integrated_testing/tests/00_console_sanity.rs b/17_kernel_symbols/kernel/tests/00_console_sanity.rs similarity index 76% rename from 12_integrated_testing/tests/00_console_sanity.rs rename to 17_kernel_symbols/kernel/tests/00_console_sanity.rs index dccb6cc2..682ea9b8 100644 --- a/12_integrated_testing/tests/00_console_sanity.rs +++ b/17_kernel_symbols/kernel/tests/00_console_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2019-2022 Andre Richter +// Copyright (c) 2019-2023 Andre Richter //! Console sanity tests - RX, TX and statistics. @@ -11,15 +11,15 @@ /// 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 bsp::console::console; - use console::interface::*; + use console::console; exception::handling_init(); - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); 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 00000000..1581a02e --- /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 00000000..09d17798 --- /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 00000000..02f51f74 --- /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 00000000..1a302911 --- /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/13_exceptions_part2_peripheral_IRQs/tests/04_exception_irq_sanity.rs b/17_kernel_symbols/kernel/tests/04_exception_irq_sanity.rs similarity index 68% rename from 13_exceptions_part2_peripheral_IRQs/tests/04_exception_irq_sanity.rs rename to 17_kernel_symbols/kernel/tests/04_exception_irq_sanity.rs index e1e02554..fcace897 100644 --- a/13_exceptions_part2_peripheral_IRQs/tests/04_exception_irq_sanity.rs +++ b/17_kernel_symbols/kernel/tests/04_exception_irq_sanity.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! IRQ handling sanity tests. @@ -10,12 +10,13 @@ #![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() -> ! { - bsp::console::qemu_bring_up_console(); + memory::init(); + bsp::driver::qemu_bring_up_console(); exception::handling_init(); exception::asynchronous::local_irq_unmask(); @@ -31,21 +32,21 @@ fn local_irq_mask_works() { // Precondition: IRQs are unmasked. assert!(exception::asynchronous::is_local_irq_masked()); - unsafe { exception::asynchronous::local_irq_mask() }; + exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); // Restore earlier state. - unsafe { exception::asynchronous::local_irq_unmask() }; + 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() }; + exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); - unsafe { exception::asynchronous::local_irq_unmask() }; + exception::asynchronous::local_irq_unmask(); assert!(exception::asynchronous::is_local_irq_masked()); } @@ -55,12 +56,12 @@ 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() }; + let first = exception::asynchronous::local_irq_mask_save(); assert!(!exception::asynchronous::is_local_irq_masked()); - let second = unsafe { exception::asynchronous::local_irq_mask_save() }; + let second = exception::asynchronous::local_irq_mask_save(); assert_ne!(first, second); - unsafe { exception::asynchronous::local_irq_restore(first) }; + 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 00000000..f778b3d8 --- /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 00000000..449ad6f9 --- /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 00000000..9ac19144 --- /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 00000000..d38b7785 --- /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 00000000..3407aa7e --- /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 00000000..5062df44 --- /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 00000000..0625f008 --- /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 00000000..38ce18f8 --- /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 00000000..e5b1fd1f --- /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 00000000..81c897bf --- /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 00000000..fff98a1f --- /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 00000000..52cf893d --- /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 00000000..2f20f060 --- /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 00000000..38961a9c --- /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 00000000..c43acb24 --- /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 00000000..32b5460a --- /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 00000000..899f9646 --- /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 00000000..61a6d6ca --- /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 = 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 = 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 00000000..93bcedd9 --- /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 00000000..743840e0 --- /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 00000000..5ba78d9d --- /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 00000000..22ab24fd --- /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 00000000..e3476485 --- /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 00000000..9ef30cd0 --- /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 00000000..701f10f1 --- /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 00000000..38eeb116 --- /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 00000000..7edf4edf --- /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 00000000..00a156d7 --- /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 00000000..bba97b8d --- /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 00000000..cab00bb3 --- /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 00000000..c2fb8dcb --- /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 00000000..2d010473 --- /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 00000000..b8033fbe --- /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 00000000..65d71b1a --- /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 00000000..49192038 --- /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 00000000..ab464081 --- /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 00000000..cdef8c58 --- /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 00000000..811ef138 --- /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 00000000..984b2e04 --- /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 00000000..21fae3b8 --- /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 00000000..ee1c3ef7 --- /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 00000000..a6af2fcc --- /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 00000000..246973bc --- /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 00000000..2dfaec8d --- /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 00000000..8d1cbfbd --- /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 00000000..256de704 --- /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 00000000..0fd16bb3 --- /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 00000000..1fc9d70e --- /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 00000000..7b7c288b --- /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 00000000..812156f4 --- /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 00000000..62f07800 --- /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 00000000..a26bff8d --- /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 00000000..b424d4be --- /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 00000000..3ce1d8d8 --- /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 00000000..30421dfa --- /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 00000000..65cf5abb --- /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 00000000..a1f55b17 --- /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 00000000..a9eaa6ac --- /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 00000000..776182fd --- /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 00000000..193a5200 --- /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 00000000..c5d58c30 --- /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 00000000..96a4d8c1 --- /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 00000000..c6263245 --- /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 00000000..2ad7e4c1 --- /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 00000000..f0363464 --- /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 00000000..e92a022b --- /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 00000000..8716a918 --- /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 00000000..b1e98328 --- /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 00000000..de612d58 --- /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 00000000..2edf8b85 --- /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 00000000..3d5f219f --- /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 00000000..2c874dd6 --- /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 00000000..38919ffe --- /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 00000000..512894f7 --- /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 00000000..e41cfaa0 --- /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 00000000..0434b13c --- /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 00000000..404e2a8a --- /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 00000000..0e079220 --- /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 00000000..344afd20 --- /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 00000000..341ffc5c --- /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 00000000..f6ac8d59 --- /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 00000000..389eb2c8 --- /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 00000000..8e303046 --- /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 00000000..becdd1b6 --- /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 00000000..fdc1d084 --- /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 00000000..5740b63e --- /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 00000000..a9d50120 --- /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 00000000..8be7a2f1 --- /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 00000000..682ea9b8 --- /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 00000000..1581a02e --- /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 00000000..09d17798 --- /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 00000000..02f51f74 --- /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 00000000..1a302911 --- /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 00000000..fcace897 --- /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 00000000..243e2fc8 --- /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 00000000..66fd0a3e --- /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 00000000..80695468 --- /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 00000000..38411af6 --- /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 00000000..6b6f0413 --- /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 00000000..6e0873dd --- /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 00000000..f778b3d8 --- /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 00000000..449ad6f9 --- /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 00000000..9ac19144 --- /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 00000000..d38b7785 --- /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 00000000..3407aa7e --- /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 00000000..5062df44 --- /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 00000000..0625f008 --- /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 00000000..38ce18f8 --- /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 00000000..e5b1fd1f --- /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 00000000..81c897bf --- /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 00000000..fff98a1f --- /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 00000000..52cf893d --- /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 00000000..2f20f060 --- /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 00000000..38961a9c --- /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 00000000..c43acb24 --- /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 00000000..32b5460a --- /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 00000000..899f9646 --- /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 00000000..61a6d6ca --- /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 = 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 = 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 00000000..5887d774 --- /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 00000000..941e2226 --- /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 00000000..5ba78d9d --- /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 00000000..22ab24fd --- /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 00000000..e3476485 --- /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 00000000..9ef30cd0 --- /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 00000000..0f642903 --- /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 00000000..38eeb116 --- /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 00000000..f9704a44 --- /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 00000000..eedf82c7 --- /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 00000000..03ebfc02 --- /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 00000000..cab00bb3 --- /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 00000000..c2fb8dcb --- /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 00000000..2d010473 --- /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 00000000..b8033fbe --- /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 00000000..1a8c8801 --- /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 00000000..49192038 --- /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 00000000..ab464081 --- /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 00000000..cdef8c58 --- /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 00000000..811ef138 --- /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 00000000..984b2e04 --- /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 00000000..21fae3b8 --- /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 00000000..ee1c3ef7 --- /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 00000000..a6af2fcc --- /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 00000000..246973bc --- /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 00000000..2dfaec8d --- /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 00000000..8d1cbfbd --- /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 00000000..7dabf793 --- /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 00000000..0fd16bb3 --- /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 00000000..1fc9d70e --- /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 00000000..7b7c288b --- /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 00000000..812156f4 --- /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 00000000..66c39597 --- /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/16_virtual_mem_part4_higher_half_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 similarity index 69% rename from 16_virtual_mem_part4_higher_half_kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs rename to 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs index f09da862..029c1e74 100644 --- a/16_virtual_mem_part4_higher_half_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 @@ -1,15 +1,22 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - -use super::{InterruptController, PendingIRQs, PeripheralIRQ}; +use super::{PendingIRQs, PeripheralIRQ}; use crate::{ bsp::device_driver::common::MMIODerefWrapper, - driver, exception, memory, synchronization, + exception, + memory::{Address, Virtual}, + synchronization, synchronization::{IRQSafeNullLock, InitStateLock}, }; +use alloc::vec::Vec; use tock_registers::{ interfaces::{Readable, Writeable}, register_structs, @@ -26,7 +33,7 @@ register_structs! { (0x00 => _reserved1), (0x10 => ENABLE_1: WriteOnly), (0x14 => ENABLE_2: WriteOnly), - (0x24 => @END), + (0x18 => @END), } } @@ -46,8 +53,7 @@ type WriteOnlyRegisters = MMIODerefWrapper; /// Abstraction for the ReadOnly parts of the associated MMIO registers. type ReadOnlyRegisters = MMIODerefWrapper; -type HandlerTable = - [Option; InterruptController::NUM_PERIPHERAL_IRQS]; +type HandlerTable = Vec>>; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -55,13 +61,11 @@ type HandlerTable = /// Representation of the peripheral interrupt controller. pub struct PeripheralIC { - 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, + ro_registers: ReadOnlyRegisters, /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. handler_table: InitStateLock, @@ -76,26 +80,27 @@ impl PeripheralIC { /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new(mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { - let addr = mmio_descriptor.start_addr().as_usize(); - + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { - 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]), + 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 { - self.ro_registers.read(|regs| { - let pending_mask: u64 = - (u64::from(regs.PENDING_2.get()) << 32) | u64::from(regs.PENDING_1.get()); + 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) - }) + PendingIRQs::new(pending_mask) } } @@ -104,46 +109,27 @@ impl PeripheralIC { //------------------------------------------------------------------------------ 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.mmio_descriptor)?.as_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, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { - let irq_number = irq.get(); + let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } - table[irq_number] = Some(descriptor); + table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } - fn enable(&self, irq: Self::IRQNumberType) { + fn enable(&self, irq: &Self::IRQNumberType) { self.wo_registers.lock(|regs| { let enable_reg = if irq.get() <= 31 { ®s.ENABLE_1 @@ -169,7 +155,7 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { 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"); + descriptor.handler().handle().expect("Error handling IRQ"); } } } @@ -184,7 +170,7 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { self.handler_table.read(|table| { for (i, opt) in table.iter().enumerate() { if let Some(handler) = opt { - info!(" {: >3}. {}", i, handler.name); + info!(" {: >3}. {}", i, handler.name()); } } }); diff --git a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs similarity index 86% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs rename to 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs index 23c09a7f..3d580975 100644 --- a/15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ b/19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -10,13 +10,14 @@ //! - use crate::{ - bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, memory, - synchronization, synchronization::IRQSafeNullLock, -}; -use core::{ - fmt, - sync::atomic::{AtomicUsize, Ordering}, + 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, @@ -219,29 +220,23 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { - mmio_descriptor: memory::mmu::MMIODescriptor, - virt_mmio_start_addr: AtomicUsize, inner: IRQSafeNullLock, - irq_number: bsp::device_driver::IRQNumber, } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -250,7 +245,7 @@ impl PL011UartInner { /// # 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, @@ -275,15 +270,7 @@ impl PL011UartInner { /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. - /// - /// # 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); - } - + 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. @@ -325,8 +312,6 @@ impl PL011UartInner { self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - - Ok(()) } /// Send a character. @@ -342,6 +327,13 @@ impl PL011UartInner { 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. @@ -399,24 +391,21 @@ 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 correct MMIO descriptors. - /// - The user must ensure to provide correct IRQ numbers. - pub const unsafe fn new( - mmio_descriptor: memory::mmu::MMIODescriptor, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { - mmio_descriptor, - virt_mmio_start_addr: AtomicUsize::new(0), - inner: IRQSafeNullLock::new(PL011UartInner::new( - mmio_descriptor.start_addr().as_usize(), - )), - irq_number, + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } } } @@ -427,46 +416,31 @@ impl PL011Uart { use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "BCM PL011 UART" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { - let virt_addr = memory::mmu::kernel_map_mmio(self.compatible(), &self.mmio_descriptor)?; - - self.inner - .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; - - self.virt_mmio_start_addr - .store(virt_addr.as_usize(), Ordering::Relaxed); + 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}; + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; - let descriptor = IRQDescriptor { - name: "BCM PL011 UART", - handler: self, - }; + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); - irq_manager().register_handler(self.irq_number, descriptor)?; - irq_manager().enable(self.irq_number); + irq_manager().register_handler(descriptor)?; + irq_manager().enable(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 { @@ -476,8 +450,12 @@ impl console::interface::Write for PL011Uart { 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 + // 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)) } @@ -514,6 +492,8 @@ impl console::interface::Statistics for PL011Uart { } } +impl console::interface::All for PL011Uart {} + impl exception::asynchronous::interface::IRQHandler for PL011Uart { fn handle(&self) -> Result<(), &'static str> { self.inner.lock(|inner| { 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 00000000..3ce1d8d8 --- /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 00000000..30421dfa --- /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 00000000..65cf5abb --- /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 00000000..a1f55b17 --- /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 00000000..a9eaa6ac --- /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 00000000..776182fd --- /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 00000000..2408b63c --- /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 00000000..c5d58c30 --- /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 00000000..8507dfc7 --- /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 00000000..ef52e368 --- /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 00000000..2ad7e4c1 --- /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 00000000..5efa9395 --- /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 00000000..05903e7c --- /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 00000000..8716a918 --- /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 00000000..b1e98328 --- /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 00000000..de612d58 --- /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 00000000..88b41b81 --- /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 00000000..3d5f219f --- /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 00000000..2c874dd6 --- /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 00000000..38919ffe --- /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 00000000..317bcc72 --- /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 00000000..ae2ea8a7 --- /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 00000000..bc611336 --- /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 00000000..cf4298fa --- /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 00000000..abe3b181 --- /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 00000000..9c17258d --- /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 00000000..344afd20 --- /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 00000000..341ffc5c --- /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 00000000..f6ac8d59 --- /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 00000000..389eb2c8 --- /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 00000000..a89f8201 --- /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 00000000..6d99beed --- /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 00000000..fdc1d084 --- /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 00000000..5740b63e --- /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 00000000..a9d50120 --- /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 00000000..8be7a2f1 --- /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 00000000..682ea9b8 --- /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 00000000..1581a02e --- /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 00000000..09d17798 --- /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 00000000..02f51f74 --- /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 00000000..1a302911 --- /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 00000000..fcace897 --- /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 00000000..243e2fc8 --- /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 00000000..66fd0a3e --- /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 00000000..80695468 --- /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 00000000..38411af6 --- /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 00000000..6b6f0413 --- /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 00000000..6e0873dd --- /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 00000000..f778b3d8 --- /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 00000000..449ad6f9 --- /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 00000000..9ac19144 --- /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 00000000..d38b7785 --- /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 00000000..70b7fa66 --- /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 00000000..3407aa7e --- /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 00000000..5062df44 --- /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 00000000..0625f008 --- /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 00000000..38ce18f8 --- /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 00000000..e5b1fd1f --- /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 00000000..81c897bf --- /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 00000000..fff98a1f --- /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 00000000..52cf893d --- /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 00000000..2f20f060 --- /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 00000000..38961a9c --- /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 00000000..c43acb24 --- /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 00000000..32b5460a --- /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 00000000..899f9646 --- /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 00000000..61a6d6ca --- /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 = 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 = 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 00000000..5887d774 --- /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 00000000..941e2226 --- /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 00000000..5ba78d9d --- /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 00000000..22ab24fd --- /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 00000000..e3476485 --- /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 00000000..9ef30cd0 --- /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 00000000..754ed74d --- /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 00000000..38eeb116 --- /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 00000000..f9704a44 --- /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 00000000..062d5912 --- /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 00000000..4a3b76d3 --- /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 00000000..cab00bb3 --- /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 00000000..c2fb8dcb --- /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 00000000..2d010473 --- /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 00000000..b8033fbe --- /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 00000000..65d71b1a --- /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 00000000..49192038 --- /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 00000000..ab464081 --- /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 00000000..a806a276 --- /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 00000000..811ef138 --- /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 00000000..984b2e04 --- /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 00000000..21fae3b8 --- /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 00000000..37ebf44b --- /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 00000000..a6af2fcc --- /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 00000000..246973bc --- /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 00000000..2dfaec8d --- /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 00000000..8d1cbfbd --- /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 00000000..7dabf793 --- /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 00000000..0fd16bb3 --- /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 00000000..1fc9d70e --- /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 00000000..7b7c288b --- /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 00000000..812156f4 --- /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 00000000..d32bd8db --- /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 00000000..b5e4974b --- /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/15_virtual_mem_part3_precomputed_tables/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 similarity index 69% rename from 15_virtual_mem_part3_precomputed_tables/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs rename to 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs index f09da862..029c1e74 100644 --- a/15_virtual_mem_part3_precomputed_tables/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 @@ -1,15 +1,22 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - -use super::{InterruptController, PendingIRQs, PeripheralIRQ}; +use super::{PendingIRQs, PeripheralIRQ}; use crate::{ bsp::device_driver::common::MMIODerefWrapper, - driver, exception, memory, synchronization, + exception, + memory::{Address, Virtual}, + synchronization, synchronization::{IRQSafeNullLock, InitStateLock}, }; +use alloc::vec::Vec; use tock_registers::{ interfaces::{Readable, Writeable}, register_structs, @@ -26,7 +33,7 @@ register_structs! { (0x00 => _reserved1), (0x10 => ENABLE_1: WriteOnly), (0x14 => ENABLE_2: WriteOnly), - (0x24 => @END), + (0x18 => @END), } } @@ -46,8 +53,7 @@ type WriteOnlyRegisters = MMIODerefWrapper; /// Abstraction for the ReadOnly parts of the associated MMIO registers. type ReadOnlyRegisters = MMIODerefWrapper; -type HandlerTable = - [Option; InterruptController::NUM_PERIPHERAL_IRQS]; +type HandlerTable = Vec>>; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -55,13 +61,11 @@ type HandlerTable = /// Representation of the peripheral interrupt controller. pub struct PeripheralIC { - 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, + ro_registers: ReadOnlyRegisters, /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. handler_table: InitStateLock, @@ -76,26 +80,27 @@ impl PeripheralIC { /// /// # Safety /// - /// - The user must ensure to provide correct MMIO descriptors. - pub const unsafe fn new(mmio_descriptor: memory::mmu::MMIODescriptor) -> Self { - let addr = mmio_descriptor.start_addr().as_usize(); - + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { - 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]), + 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 { - self.ro_registers.read(|regs| { - let pending_mask: u64 = - (u64::from(regs.PENDING_2.get()) << 32) | u64::from(regs.PENDING_1.get()); + 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) - }) + PendingIRQs::new(pending_mask) } } @@ -104,46 +109,27 @@ impl PeripheralIC { //------------------------------------------------------------------------------ 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.mmio_descriptor)?.as_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, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { - let irq_number = irq.get(); + let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } - table[irq_number] = Some(descriptor); + table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } - fn enable(&self, irq: Self::IRQNumberType) { + fn enable(&self, irq: &Self::IRQNumberType) { self.wo_registers.lock(|regs| { let enable_reg = if irq.get() <= 31 { ®s.ENABLE_1 @@ -169,7 +155,7 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { 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"); + descriptor.handler().handle().expect("Error handling IRQ"); } } } @@ -184,7 +170,7 @@ impl exception::asynchronous::interface::IRQManager for PeripheralIC { self.handler_table.read(|table| { for (i, opt) in table.iter().enumerate() { if let Some(handler) = opt { - info!(" {: >3}. {}", i, handler.name); + info!(" {: >3}. {}", i, handler.name()); } } }); diff --git a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs similarity index 86% rename from 14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs rename to 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs index 23c09a7f..3d580975 100644 --- a/14_virtual_mem_part2_mmio_remap/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ b/20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -10,13 +10,14 @@ //! - use crate::{ - bsp, bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception, memory, - synchronization, synchronization::IRQSafeNullLock, -}; -use core::{ - fmt, - sync::atomic::{AtomicUsize, Ordering}, + 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, @@ -219,29 +220,23 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { - mmio_descriptor: memory::mmu::MMIODescriptor, - virt_mmio_start_addr: AtomicUsize, inner: IRQSafeNullLock, - irq_number: bsp::device_driver::IRQNumber, } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -250,7 +245,7 @@ impl PL011UartInner { /// # 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, @@ -275,15 +270,7 @@ impl PL011UartInner { /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. - /// - /// # 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); - } - + 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. @@ -325,8 +312,6 @@ impl PL011UartInner { self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); - - Ok(()) } /// Send a character. @@ -342,6 +327,13 @@ impl PL011UartInner { 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. @@ -399,24 +391,21 @@ 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 correct MMIO descriptors. - /// - The user must ensure to provide correct IRQ numbers. - pub const unsafe fn new( - mmio_descriptor: memory::mmu::MMIODescriptor, - irq_number: bsp::device_driver::IRQNumber, - ) -> Self { + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { - mmio_descriptor, - virt_mmio_start_addr: AtomicUsize::new(0), - inner: IRQSafeNullLock::new(PL011UartInner::new( - mmio_descriptor.start_addr().as_usize(), - )), - irq_number, + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } } } @@ -427,46 +416,31 @@ impl PL011Uart { use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { - "BCM PL011 UART" + Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { - let virt_addr = memory::mmu::kernel_map_mmio(self.compatible(), &self.mmio_descriptor)?; - - self.inner - .lock(|inner| inner.init(Some(virt_addr.as_usize())))?; - - self.virt_mmio_start_addr - .store(virt_addr.as_usize(), Ordering::Relaxed); + 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}; + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; - let descriptor = IRQDescriptor { - name: "BCM PL011 UART", - handler: self, - }; + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); - irq_manager().register_handler(self.irq_number, descriptor)?; - irq_manager().enable(self.irq_number); + irq_manager().register_handler(descriptor)?; + irq_manager().enable(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 { @@ -476,8 +450,12 @@ impl console::interface::Write for PL011Uart { 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 + // 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)) } @@ -514,6 +492,8 @@ impl console::interface::Statistics for PL011Uart { } } +impl console::interface::All for PL011Uart {} + impl exception::asynchronous::interface::IRQHandler for PL011Uart { fn handle(&self) -> Result<(), &'static str> { self.inner.lock(|inner| { 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 00000000..3ce1d8d8 --- /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 00000000..30421dfa --- /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 00000000..65cf5abb --- /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 00000000..d02909e3 --- /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 00000000..a9eaa6ac --- /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 00000000..82935adb --- /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 00000000..2408b63c --- /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 00000000..c5d58c30 --- /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 00000000..f8c9b6a1 --- /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 00000000..ef52e368 --- /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 00000000..2ad7e4c1 --- /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 00000000..5efa9395 --- /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 00000000..05903e7c --- /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 00000000..8716a918 --- /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 00000000..b1e98328 --- /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 00000000..de612d58 --- /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 00000000..88b41b81 --- /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 00000000..3d5f219f --- /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 00000000..2c874dd6 --- /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 00000000..38919ffe --- /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 00000000..317bcc72 --- /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 00000000..249b2718 --- /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 00000000..bc611336 --- /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 00000000..cf4298fa --- /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 00000000..abe3b181 --- /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 00000000..9c17258d --- /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 00000000..344afd20 --- /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 00000000..341ffc5c --- /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 00000000..f6ac8d59 --- /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 00000000..389eb2c8 --- /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 00000000..a89f8201 --- /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 00000000..6d99beed --- /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 00000000..fdc1d084 --- /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 00000000..5740b63e --- /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 00000000..5767a3e6 --- /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 00000000..8be7a2f1 --- /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 00000000..682ea9b8 --- /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 00000000..1581a02e --- /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 00000000..09d17798 --- /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 00000000..02f51f74 --- /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 00000000..1a302911 --- /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 00000000..fcace897 --- /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 00000000..243e2fc8 --- /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 00000000..66fd0a3e --- /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 00000000..80695468 --- /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 00000000..38411af6 --- /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 00000000..6b6f0413 --- /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 00000000..6e0873dd --- /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 00000000..d65f1a92 --- /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 00000000..449ad6f9 --- /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 00000000..9ac19144 --- /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 00000000..d38b7785 --- /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 00000000..70b7fa66 --- /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 00000000..3407aa7e --- /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 00000000..5062df44 --- /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 00000000..16724a07 --- /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 00000000..38ce18f8 --- /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 00000000..e5b1fd1f --- /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 00000000..81c897bf --- /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 00000000..fff98a1f --- /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 00000000..52cf893d --- /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 00000000..2f20f060 --- /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 00000000..38961a9c --- /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 00000000..c43acb24 --- /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 00000000..32b5460a --- /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 00000000..899f9646 --- /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 00000000..61a6d6ca --- /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 = 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 = 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 00000000..5887d774 --- /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 00000000..941e2226 --- /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 00000000..5ba78d9d --- /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 00000000..22ab24fd --- /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 7ac3b89e..7460e048 100644 --- a/Gemfile +++ b/Gemfile @@ -11,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 d36a7e18..af7f918f 100644 --- a/LICENSE-MIT +++ b/LICENSE-MIT @@ -1,6 +1,6 @@ MIT License -Copyright (C) 2018-2022 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.md b/README.md index 66e60d44..7267f440 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ The tutorials are primarily targeted at **Linux**-based distributions. Most stuf ### 🚀 The tl;dr Version -1. [Install Docker Desktop][install_docker]. +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](rust-toolchain) file. What's left for us to do is: @@ -81,10 +81,16 @@ The tutorials are primarily targeted at **Linux**-based distributions. Most stuf 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 - bundle install --path .vendor/bundle --without development + 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/ @@ -113,7 +119,7 @@ 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 diff --git a/X1_JTAG_boot/.vscode/settings.json b/X1_JTAG_boot/.vscode/settings.json index 0a8d7c09..bfa278e9 100644 --- a/X1_JTAG_boot/.vscode/settings.json +++ b/X1_JTAG_boot/.vscode/settings.json @@ -1,9 +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.overrideCommand": ["make", "check"], - "rust-analyzer.lens.debug": false, - "rust-analyzer.lens.run": false + "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 ef4ed866..9020b4f9 100644 --- a/X1_JTAG_boot/Cargo.lock +++ b/X1_JTAG_boot/Cargo.lock @@ -3,10 +3,10 @@ version = 3 [[package]] -name = "cortex-a" -version = "7.2.0" +name = "aarch64-cpu" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bd91f65ccd348bb2d043d98c5b34af141ecef7f102147f59bf5898f6e734ad" +checksum = "3aceb88e55ba626a5479279268d009a92d9d00eacce0de1b8c236c7ad31b7225" dependencies = [ "tock-registers", ] @@ -15,12 +15,12 @@ dependencies = [ name = "mingo" version = "0.8.0" dependencies = [ - "cortex-a", + "aarch64-cpu", "tock-registers", ] [[package]] name = "tock-registers" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee8fba06c1f4d0b396ef61a54530bb6b28f0dc61c38bc8bc5a5a48161e6282e" +checksum = "696941a0aee7e276a165a978b37918fd5d22c55c3d6bda197813070ca9c0f21c" diff --git a/X1_JTAG_boot/Cargo.toml b/X1_JTAG_boot/Cargo.toml index 638d4de1..e310c371 100644 --- a/X1_JTAG_boot/Cargo.toml +++ b/X1_JTAG_boot/Cargo.toml @@ -23,8 +23,8 @@ path = "src/main.rs" [dependencies] # Optional dependencies -tock-registers = { version = "0.7.x", default-features = false, features = ["register_types"], 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 = "7.x.x" } +aarch64-cpu = { version = "9.x.x" } diff --git a/X1_JTAG_boot/Makefile b/X1_JTAG_boot/Makefile index 3f6b230a..b13f0dfb 100644 --- a/X1_JTAG_boot/Makefile +++ b/X1_JTAG_boot/Makefile @@ -1,9 +1,10 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2018-2022 Andre Richter +## Copyright (c) 2018-2023 Andre Richter -include ../common/format.mk include ../common/docker.mk +include ../common/format.mk +include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values @@ -54,14 +55,14 @@ export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- -KERNEL_LINKER_SCRIPT = link.ld - -LAST_BUILD_CONFIG = target/$(BSP).build_config +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_RAW).d)) $(LAST_BUILD_CONFIG) +KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) @@ -84,7 +85,6 @@ COMPILER_ARGS = --target=$(TARGET) \ 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 @@ -146,7 +146,7 @@ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") - @printf '%s KiB\n' `du -k $(KERNEL_BIN) | cut -f1` + $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation @@ -204,7 +204,6 @@ objdump: $(KERNEL_ELF) @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ - --section .got \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ @@ -214,12 +213,6 @@ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt -##------------------------------------------------------------------------------ -## Helper target for rust-analyzer -##------------------------------------------------------------------------------ -check: - @RUSTFLAGS="$(RUSTFLAGS)" $(CHECK_CMD) --message-format=json - ##-------------------------------------------------------------------------------------------------- diff --git a/X1_JTAG_boot/jtag_boot_rpi3.img b/X1_JTAG_boot/jtag_boot_rpi3.img index 584c5a6e..f472e766 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 4ebab5bf..b4bca1b7 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 4414ac6a..602c9789 100644 --- a/X1_JTAG_boot/src/_arch/aarch64/cpu.rs +++ b/X1_JTAG_boot/src/_arch/aarch64/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! @@ -11,7 +11,7 @@ //! //! crate::cpu::arch_cpu -use cortex_a::asm; +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 index 2f9654c7..2a6c4649 100644 --- a/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.rs +++ b/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! @@ -11,8 +11,13 @@ //! //! crate::cpu::boot::arch_boot +use core::arch::global_asm; + // Assembly counterpart to this file. -core::arch::global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); //-------------------------------------------------------------------------------------------------- // Public Code diff --git a/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.s b/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.s index 7d445a93..78f8c321 100644 --- a/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.s +++ b/X1_JTAG_boot/src/_arch/aarch64/cpu/boot.s @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions @@ -18,8 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -.equ _core_id_mask, 0b11 - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -31,7 +29,7 @@ _start: // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 - and x1, x1, _core_id_mask + 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 @@ -54,6 +52,14 @@ _start: 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 diff --git a/X1_JTAG_boot/src/_arch/aarch64/time.rs b/X1_JTAG_boot/src/_arch/aarch64/time.rs index c814219c..eb97b8be 100644 --- a/X1_JTAG_boot/src/_arch/aarch64/time.rs +++ b/X1_JTAG_boot/src/_arch/aarch64/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Architectural timer primitives. //! @@ -11,111 +11,154 @@ //! //! crate::time::arch_time -use crate::{time, warn}; -use core::time::Duration; -use cortex_a::{asm::barrier, registers::*}; -use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; +#[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; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -impl GenericTimer { - #[inline(always)] - fn read_cntpct(&self) -> u64 { - // Prevent that the counter is read ahead of time due to out-of-order execution. - unsafe { barrier::isb(barrier::SY) }; - CNTPCT_EL0.get() - } +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) } } -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the time manager. -pub fn time_manager() -> &'static impl time::interface::TimeManager { - &TIME_MANAGER +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 current_count: u64 = self.read_cntpct() * NS_PER_S; - let frq: u64 = CNTFRQ_EL0.get() as u64; + // 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(); - let x = match frq.checked_mul(duration.as_nanos() as u64) { - #[allow(unused_imports)] - 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 - }; - - #[allow(unused_imports)] - 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 824787f6..246973bc 100644 --- a/X1_JTAG_boot/src/bsp.rs +++ b/X1_JTAG_boot/src/bsp.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. diff --git a/X1_JTAG_boot/src/bsp/device_driver.rs b/X1_JTAG_boot/src/bsp/device_driver.rs index 6e9bf8f3..64049a4c 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-2022 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 b4b7906e..1c343d1d 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-2022 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 dbb4beaa..8e57dfed 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-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. @@ -108,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 { @@ -125,7 +122,7 @@ pub struct GPIO { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { @@ -143,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. @@ -189,7 +186,13 @@ impl GPIOInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + /// Create an instance. /// /// # Safety @@ -214,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 878ea567..d92612ea 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,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! @@ -167,18 +167,15 @@ enum BlockingMode { NonBlocking, } -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -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 { @@ -186,7 +183,7 @@ pub struct PL011Uart { } //-------------------------------------------------------------------------------------------------- -// Public Code +// Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { @@ -326,7 +323,13 @@ impl fmt::Write for PL011UartInner { } } +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + /// Create an instance. /// /// # Safety @@ -346,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> { @@ -364,7 +367,7 @@ 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)) } @@ -400,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 fd9e988e..dfe7d8ef 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-2022 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 f8dbc1f4..b6d48fdd 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-2022 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 a247032f..00000000 --- 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-2022 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 85fb89e4..65cf5abb 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-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Processor code. diff --git a/X1_JTAG_boot/src/bsp/raspberrypi/driver.rs b/X1_JTAG_boot/src/bsp/raspberrypi/driver.rs index b5538baa..2a80ee2c 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-2022 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 00000000..32f6defa --- /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 007afd4a..00000000 --- a/X1_JTAG_boot/src/bsp/raspberrypi/link.ld +++ /dev/null @@ -1,72 +0,0 @@ -/* 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 - .got : ALIGN(8) { *(.got) } :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 -} diff --git a/X1_JTAG_boot/src/bsp/raspberrypi/memory.rs b/X1_JTAG_boot/src/bsp/raspberrypi/memory.rs index 27be8590..cdca14b8 100644 --- a/X1_JTAG_boot/src/bsp/raspberrypi/memory.rs +++ b/X1_JTAG_boot/src/bsp/raspberrypi/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. diff --git a/X1_JTAG_boot/src/console.rs b/X1_JTAG_boot/src/console.rs index e49e241f..a83f86fe 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-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! System console. +mod null_console; + +use crate::synchronization::{self, NullLock}; + //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -49,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 00000000..e92a022b --- /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 62503fb4..67ab79c0 100644 --- a/X1_JTAG_boot/src/cpu.rs +++ b/X1_JTAG_boot/src/cpu.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Processor code. diff --git a/X1_JTAG_boot/src/cpu/boot.rs b/X1_JTAG_boot/src/cpu/boot.rs index 8091dac3..b1e98328 100644 --- a/X1_JTAG_boot/src/cpu/boot.rs +++ b/X1_JTAG_boot/src/cpu/boot.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2021-2022 Andre Richter +// Copyright (c) 2021-2023 Andre Richter //! Boot code. diff --git a/X1_JTAG_boot/src/driver.rs b/X1_JTAG_boot/src/driver.rs index 2fcc7562..53592c66 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-2022 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 6e6cf909..7ab191f5 100644 --- a/X1_JTAG_boot/src/main.rs +++ b/X1_JTAG_boot/src/main.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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. //! @@ -105,9 +107,13 @@ //! 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] @@ -127,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/panic_wait.rs b/X1_JTAG_boot/src/panic_wait.rs index f851e0d8..5776aca8 100644 --- a/X1_JTAG_boot/src/panic_wait.rs +++ b/X1_JTAG_boot/src/panic_wait.rs @@ -1,32 +1,16 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2018-2022 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; - - unsafe { bsp::console::panic_console_out().write_fmt(args).unwrap() }; -} - -/// Prints with a newline - only use from the panic handler. -/// -/// Carbon copy from -#[macro_export] -macro_rules! panic_println { - ($($arg:tt)*) => ({ - _panic_print(format_args_nl!($($arg)*)); - }) -} - /// Stop immediately if called a second time. /// /// # Note @@ -58,8 +42,6 @@ fn panic_prevent_reenter() { #[panic_handler] fn panic(info: &PanicInfo) -> ! { - use crate::time::interface::TimeManager; - // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); @@ -69,7 +51,7 @@ fn panic(info: &PanicInfo) -> ! { _ => ("???", 0, 0), }; - panic_println!( + println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", diff --git a/X1_JTAG_boot/src/print.rs b/X1_JTAG_boot/src/print.rs index 9ec13a28..8e303046 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-2022 Andre Richter +// Copyright (c) 2018-2023 Andre Richter //! Printing. -use crate::{bsp, console}; +use crate::console; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -13,9 +13,7 @@ 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. @@ -41,8 +39,6 @@ macro_rules! println { #[macro_export] macro_rules! info { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -52,8 +48,6 @@ macro_rules! info { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -69,8 +63,6 @@ macro_rules! info { #[macro_export] macro_rules! warn { ($string:expr) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( @@ -80,8 +72,6 @@ macro_rules! warn { )); }); ($format_string:expr, $($arg:tt)*) => ({ - use $crate::time::interface::TimeManager; - let timestamp = $crate::time::time_manager().uptime(); $crate::print::_print(format_args_nl!( diff --git a/X1_JTAG_boot/src/synchronization.rs b/X1_JTAG_boot/src/synchronization.rs index d5653a19..94c83de1 100644 --- a/X1_JTAG_boot/src/synchronization.rs +++ b/X1_JTAG_boot/src/synchronization.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! @@ -26,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; } } @@ -67,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 6d92b196..19a48a88 100644 --- a/X1_JTAG_boot/src/time.rs +++ b/X1_JTAG_boot/src/time.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 // -// Copyright (c) 2020-2022 Andre Richter +// Copyright (c) 2020-2023 Andre Richter //! Timer primitives. @@ -8,30 +8,46 @@ #[path = "_arch/aarch64/time.rs"] mod arch_time; +use core::time::Duration; + //-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports +// Public Definitions //-------------------------------------------------------------------------------------------------- -pub use arch_time::time_manager; + +/// Provides time management functions. +pub struct TimeManager; //-------------------------------------------------------------------------------------------------- -// Public Definitions +// Global instances //-------------------------------------------------------------------------------------------------- -/// Timekeeping interfaces. -pub mod interface { - use core::time::Duration; +static TIME_MANAGER: TimeManager = TimeManager::new(); - /// Time management functions. - pub trait TimeManager { - /// The timer's resolution. - fn resolution(&self) -> Duration; +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- - /// The uptime since power-on of the device. - /// - /// This includes time consumed by firmware and bootloaders. - fn uptime(&self) -> Duration; +/// 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 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. - fn spin_for(&self, duration: Duration); + /// Spin for a given duration. + #[cfg(feature = "bsp_rpi3")] + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) } } diff --git a/common/operating_system.mk b/common/operating_system.mk new file mode 100644 index 00000000..90172f77 --- /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 index 62feebf2..2b90dd71 100755 --- a/common/serial/minipush.rb +++ b/common/serial/minipush.rb @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2020-2022 Andre Richter +# Copyright (c) 2020-2023 Andre Richter require_relative 'miniterm' require 'ruby-progressbar' @@ -82,7 +82,7 @@ class MiniPush < MiniTerm # override def handle_reconnect(_error) - connetion_reset + connection_reset puts puts "[#{@name_short}] ⚡ " \ @@ -107,15 +107,15 @@ class MiniPush < MiniTerm 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 'Minipush 1.0'.cyan diff --git a/common/serial/minipush/progressbar_patch.rb b/common/serial/minipush/progressbar_patch.rb index 1862a234..e90b9bd1 100644 --- a/common/serial/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-2022 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/common/serial/miniterm.rb b/common/serial/miniterm.rb index 996e1d3f..db2ddac5 100755 --- a/common/serial/miniterm.rb +++ b/common/serial/miniterm.rb @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2020-2022 Andre Richter +# Copyright (c) 2020-2023 Andre Richter require 'rubygems' require 'bundler/setup' @@ -88,7 +88,7 @@ class MiniTerm end end - def connetion_reset + def connection_reset @target_serial&.close @target_serial = nil @host_console.cooked! @@ -96,14 +96,14 @@ class MiniTerm # When the serial lost power or was removed during R/W operation. def handle_reconnect(_error) - connetion_reset + 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}" @@ -120,15 +120,15 @@ class MiniTerm 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 diff --git a/common/tests/boot_test.rb b/common/tests/boot_test.rb index 0dbef3df..5885c727 100644 --- a/common/tests/boot_test.rb +++ b/common/tests/boot_test.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter require_relative 'console_io_test' diff --git a/common/tests/console_io_test.rb b/common/tests/console_io_test.rb index cfb45a2b..ea9d93e2 100644 --- a/common/tests/console_io_test.rb +++ b/common/tests/console_io_test.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2019-2022 Andre Richter +# Copyright (c) 2019-2023 Andre Richter require 'expect' require 'pty' @@ -27,9 +27,9 @@ end # Monkey-patch IO so that we get access to the buffer of a previously unsuccessful expect(). class IO - # rubocop:disable Naming:MethodName - attr_reader :unusedBuf - # rubocop:enable Naming:MethodName + def unused_buf + @unusedBuf + end end # A wrapper class that records characters that have been received from a PTY. @@ -43,7 +43,7 @@ class PTYLoggerWrapper def expect(pattern, timeout) result = @pty.expect(pattern, timeout) @log << if result.nil? - @pty.unusedBuf + @pty.unused_buf else result end diff --git a/common/tests/dispatch.rb b/common/tests/dispatch.rb index 13ae3af8..96793710 100755 --- a/common/tests/dispatch.rb +++ b/common/tests/dispatch.rb @@ -3,26 +3,32 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2019-2022 Andre Richter +# Copyright (c) 2019-2023 Andre Richter -require_relative 'boot_test' -require_relative 'console_io_test' -require_relative 'exit_code_test' +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 'tests/boot_test_string.rb' # provides 'EXPECTED_PRINT' + 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 = "tests/#{test_name}.rb" + 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' diff --git a/common/tests/exit_code_test.rb b/common/tests/exit_code_test.rb index 4bcdc7af..900510d4 100644 --- a/common/tests/exit_code_test.rb +++ b/common/tests/exit_code_test.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2019-2022 Andre Richter +# Copyright (c) 2019-2023 Andre Richter require 'English' require_relative 'test' diff --git a/common/tests/test.rb b/common/tests/test.rb index 7ba5b7c4..65afad0b 100644 --- a/common/tests/test.rb +++ b/common/tests/test.rb @@ -2,13 +2,12 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2019-2022 Andre Richter +# Copyright (c) 2019-2023 Andre Richter # Test base class. class Test INDENT = ' ' - # rubocop:disable Style/RedundantInitialize def initialize # Template instance variables. # @test_name @@ -16,7 +15,6 @@ class Test # @test_output # @test_error end - # rubocop:enable Style/RedundantInitialize private diff --git a/contributor_setup.sh b/contributor_setup.sh index 8bad881f..26a4059e 100755 --- a/contributor_setup.sh +++ b/contributor_setup.sh @@ -10,7 +10,7 @@ then echo "'bundle' could not be found. Please install Ruby and Bundler." exit fi -bundle config set path '.vendor/bundle' +bundle config set --local path '.vendor/bundle' bundle install # @@ -31,6 +31,6 @@ then echo "'curl' could not be found. Please install it." exit fi -curl -L -o ./install-misspell.sh https://git.io/misspell +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/doc/18_stack_frames.png b/doc/18_stack_frames.png new file mode 100644 index 00000000..781732f6 Binary files /dev/null and b/doc/18_stack_frames.png differ diff --git a/docker/rustembedded-osdev-utils/Dockerfile b/docker/rustembedded-osdev-utils/Dockerfile index 7aa705df..e8cb2cb5 100644 --- a/docker/rustembedded-osdev-utils/Dockerfile +++ b/docker/rustembedded-osdev-utils/Dockerfile @@ -1,7 +1,7 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2017-2022 Andre Richter -## Copyright (c) 2019-2022 Nao Taco +## Copyright (c) 2017-2023 Andre Richter +## Copyright (c) 2019-2023 Nao Taco FROM ubuntu:20.04 ARG VCS_REF diff --git a/docker/rustembedded-osdev-utils/Makefile b/docker/rustembedded-osdev-utils/Makefile index 8127375d..57acd995 100644 --- a/docker/rustembedded-osdev-utils/Makefile +++ b/docker/rustembedded-osdev-utils/Makefile @@ -1,6 +1,6 @@ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## -## Copyright (c) 2019-2022 Andre Richter +## Copyright (c) 2019-2023 Andre Richter # Reference followed: https://www.docker.com/blog/getting-started-with-docker-for-arm-on-linux diff --git a/rust-toolchain.toml b/rust-toolchain.toml index a24afec2..a554c0a9 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly-2022-04-10" -components = ["llvm-tools-preview", "rustfmt"] +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 a926cd2c..2b120d6b 100755 --- a/utils/devtool.rb +++ b/utils/devtool.rb @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2020-2022 Andre Richter +# Copyright (c) 2020-2023 Andre Richter require 'rubygems' require 'bundler/setup' @@ -94,11 +94,11 @@ class TutorialCrate private def boot_test? - Dir.exist?("#{@folder}/tests") + Dir.exist?("#{@folder}/tests") || Dir.exist?("#{@folder}/kernel/tests") end def unit_integration_tests? - !Dir.glob("#{@folder}/tests/00_*.rs").empty? + !Dir.glob("#{@folder}/kernel/tests/00_*.rs").empty? end end @@ -108,7 +108,7 @@ class DevTool @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 @@ -233,7 +233,7 @@ class DevTool 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) @@ -301,7 +301,15 @@ class DevTool # 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 @@ -321,9 +329,9 @@ class DevTool end end -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- ## Execution starts here -##-------------------------------------------------------------------------------------------------- +## ------------------------------------------------------------------------------------------------- tool = DevTool.new cmd = ARGV[0] commands = tool.public_methods(false).sort @@ -335,4 +343,5 @@ else puts puts 'Commands:' commands.each { |m| puts " #{m}" } + exit(1) end diff --git a/utils/devtool/copyright.rb b/utils/devtool/copyright.rb index e1741554..d1aed851 100644 --- a/utils/devtool/copyright.rb +++ b/utils/devtool/copyright.rb @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2018-2022 Andre Richter +# Copyright (c) 2018-2023 Andre Richter require 'rubygems' require 'bundler/setup' diff --git a/utils/diff_tut_folders.bash b/utils/diff_tut_folders.bash index f4e6d107..cdd9880e 100755 --- a/utils/diff_tut_folders.bash +++ b/utils/diff_tut_folders.bash @@ -2,14 +2,13 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2018-2022 Andre Richter +# Copyright (c) 2018-2023 Andre Richter DIFF=$( diff -uNr \ -x README.md \ -x README.CN.md \ -x README.ES.md \ - -x kernel \ -x kernel8.img \ -x Cargo.lock \ -x target \ @@ -17,7 +16,7 @@ DIFF=$( | 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 README.ES.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/update_copyright.rb b/utils/update_copyright.rb index 2bfd2895..dc1abbf4 100755 --- a/utils/update_copyright.rb +++ b/utils/update_copyright.rb @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT OR Apache-2.0 # -# Copyright (c) 2021-2022 Andre Richter +# Copyright (c) 2021-2023 Andre Richter require 'date'